c++中访问私有属性
在c++的类中,属性通常有三种类型,public、private、protected,下面以员工介绍类作为案例理解。
具体实现
#include<iostream>
using std::string;
class Employee{
public:
string Name;
string Company;
int Age;
void IntroduceYourself(){
std::cout << "Name - " << Name << std::endl;
std::cout << "Company - " << Company << std::endl;
std::cout << "Age - " << Age << std::endl;
}
Employee(string name,string company, int age){
Name = name;
Company = company;
Age = age;
}
};
int main()
{
Employee employee1("Tom", "ali", 23);
std::cout << "name is " << employee1.Name << std::endl;
employee1.IntroduceYourself();
Employee employee2("Bob", "yamaxun", 35);
employee2.IntroduceYourself();
}
在以上代码中,定义了一个Employee员工类,public属性有姓名、公司和年龄,类方法IntroduceYourself打印三个员工属性,构造函数Employee便于传参。
输出:
#include<iostream>
using std::string;
class Employee{
private:
string Name;
string Company;
int Age;
public:
void setName(string name){
Name = name;
}
string getName(){
return Name;
}
void setCompany(string company){
Company = company;
}
string getCompany(){
return Company;
}
void setAge(int age){
Age = age;
}
int getAge(){
return Age;
}
void IntroduceYourself(){
std::cout << "Name - " << Name << std::endl;
std::cout << "Company - " << Company << std::endl;
std::cout << "Age - " << Age << std::endl;
}
Employee(string name,string company, int age){
Name = name;
Company = company;
Age = age;
}
};
int main()
{
Employee employee1("Tom", "ali", 23);
employee1.IntroduceYourself();
employee1.setCompany("huawei");
Employee employee2("Bob", "yamaxun", 35);
employee2.IntroduceYourself();
employee2.setAge(25);
std::cout << employee2.getAge() << std::endl;
employee2.IntroduceYourself();
}
输出:
在以上代码中,姓名、公司和年龄为private属性,需要使用public中的set和get方法去获取。