为什么该程序产生编译错误:
proxy.cpp:在成员函数“ void ProxyCar :: MoveCar()”中:
proxy.cpp:59:错误:“ int Driver :: age”是私有的
proxy.cpp:81:错误:在此上下文中
class Car
{
public:
void MoveCar()
{
cout << "Car has been driven";
}
};
class Driver
{
private:
int age;
public:
int get() { return age; }
void set(int value) { age = value; }
Driver(int age):age(age){}
};
class ProxyCar
{
private:
Driver driver;
Car *realCar;
public:
ProxyCar(Driver driver): driver(driver), realCar (new Car) {}
void MoveCar()
{
if (driver.age <= 16)
cout << "Sorry the driver is too young to drive";
else
realCar->MoveCar();
}
};
int main()
{
Driver d(16);
ProxyCar p(d);
p.MoveCar();
return 0;
}
我正在尝试访问ProxyCar中的Driver对象。该行导致错误。
如果(driver.age
最佳答案
因为age
是Driver
类中的私有成员。
您是否打算这样做:
if (driver.get()<= 16)
cout << "Sorry the driver is too young to drive";
else
realCar->MoveCar();
关于c++ - 访问相同类的私有(private)成员时,为什么会出现编译错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20629420/