爲什麼這個節目給編譯錯誤:爲什麼訪問同一類的私有成員時,編譯錯誤
proxy.cpp:在成員函數 'void ProxyCar :: MoveCar()': proxy.cpp:59:錯誤:「詮釋驅動程序::年齡」是私人 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驅動程序對象之內。此行導致錯誤。 if(driver.age < = 16)
ProxyCar和驅動程序是不同的類別。只有Driver對象被允許訪問Driver的私有成員。 –