2017-04-09 95 views
-1

我正在用C++編寫一個程序,我必須使用合成。我有一個服務班,一個車輛和一個約會班。在我的車輛類中,我有一個服務對象。我想在車輛類中的一個函數中使用服務類中的服務變量,但我得到C2248錯誤。如果我在該類中有一個服務對象,我不應該能夠使用obj.variablename訪問數據嗎?我怎樣才能訪問這些變量?使用合成C++訪問私有數據成員

下面的代碼片段:

class service 
{ 
    int serviceopt; 
    int months_service; 
    char description[150]; 
    date last_service; 
    date next_service; 
    int error; 
    //code 
}; 
class vehicle 
{ 
    service obj; 
    char model[50]; 
    char license[10]; 
    int year; 
    //code 
    void display_license(void) 
    { 
    cout<<endl<<"License= "<<license; 
    cout<<endl<<"Vehicle model "<<model; 
    cout<<endl<<"Make year "<<year; 
    cout<<endl<<"Service to be done: "<<obj.description; //cannot access the variable 
    } 
}; 
+1

'private'字段只能在同一個類的範圍內或通過它的* friend * s來訪問。/C++ 101 – DeiDei

+2

[C++訪問私有成員在基類中組成兩個類時可能的重複](http://stackoverflow.com/questions/31230928/c-access-private-member-in-composition-of-兩班從 - 基類) – Shibli

回答

0

我覺得定義如下:

struct service 
{ 
    int serviceopt; 
    int months_service; 
    char description[150]; 
    date last_service; 
    date next_service; 
    int error; 
    //code 
}; 

然後

class vehicle 
{ 
private: 
    struct service obj; 
    // other members 
    // ... 
} 

可滿足您的要求。