我宣布这个课后:
class Person
{
private:
int age;
public:
void setAge(int age);
int getAge();
}
<。>在.h文件中我实现了set和get方法:
void Person::setAge(int age)
{
this->age = age;
}
int Person::getAge()
{
return age;
}
在.cpp文件中
我正在尝试从另一个继承自'Person'类的另一个类'Employee'中预订对象后,从main.cpp文件中访问age变量
Employee emp;
cin >> emp.age;
但是我收到了这个错误:
成员Person :: age无法访问
答案 0 :(得分:1)
使用getters和setter访问年龄。由于age是私有变量,私有变量不会被继承,因此您无法从employee类访问age变量。
答案 1 :(得分:0)
您有阅读当前age
的访问者,以及撰写当前年龄的增变器。要使用您的类,您需要读入一个临时变量,然后使用 mutator 来更改它。
Employee emp;
int employee_age; // temporary variable to read in age...
cin >> employee_age;
// using the mutator to set age
emp.setAge(employee_age);
答案 2 :(得分:0)
您需要使用getter和setter方法,而不是直接尝试访问该字段。
emp.getAge() //will give you the current age.
emp.setAge(25) //will set the age to 25.
你的例子是:
cin >> emp.getAge()