2013-12-17 30 views
0

爲什麼這個節目給編譯錯誤:爲什麼訪問同一類的私有成員時,編譯錯誤

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)

+2

ProxyCar和驅動程序是不同的類別。只有Driver對象被允許訪問Driver的私有成員。 –

回答

3

Driver::ageprivate的成員class Driver。因此,只有class Driver

的成員才能訪問,但您可以使用訪問方法讓外部世界訪問private成員。

class Driver 
{ 
    private: 
     int age; 

    public: 
     int get_age() { return age; } 
}; 

並使用訪問器方法獲取該類的private成員。

if (driver.get_age() <= 16) 
    cout << "Sorry the driver is too young to drive"; 
else 
    realCar->MoveCar(); 

更多關於訪問修飾符:http://en.wikipedia.org/wiki/Access_modifiers

0

您正在訪問的Driver的私有成員。這是一個單獨的課程,您無法看到其私人成員。

4

因爲ageDriver類中的私人成員。

你打算這樣做:

 if (driver.get()<= 16) 
     cout << "Sorry the driver is too young to drive"; 
    else 
     realCar->MoveCar(); 
相關問題