2017-07-06 33 views
-3

我對如何在繼承中使用構圖感到困惑。基於我的理解,我寫了一個簡單的例子。請幫助我。
1)如果上述代碼正確與否? 2)我的多重繼承實現是否正確? 3)我在Employees類中進行繼承和組合。那是對的嗎 ?如何在C++中使用組合使用多繼承?

class address 
{ 
private: 

public: 

    struct MyStruct 
    { 
     int houseno; 
     string colony; 
     string city;  
    }; 

    MyStruct m; 
    //shows the address 
    void get_address() 
    { 
     cout << m.houseno; 
     cout<<m.colony; 
     cout << m.city; 
    } 
}; 
class telephoneNo 
{ 
private: 
    string c; 
public: 

    // takes the telephoneNo of the employee from user and pass to local variable 
    void set_telephone(string d) 
    { 
     c = d; 
    } 
    void get_telephone() 
    { 
     cout << c; 
    } 
}; 
//multiple level inheritance 
class employee :public address, public telephoneNo 
{ 
    private: 
     string name; 
    public: 
    address obj;  //composition 
    telephoneNo obj2; // composition 

    void employee_name(string a) 
    { 
     name = a; 
    } 
    void show_emplyeeDetail() 
    { 
     cout << "Employee's Name is: "; 
     cout << name<<endl; 
     cout << "Employee's Address is: "; 
     obj.get_address(); 
     cout<<endl; 
     cout << "Employee's Telephnoe no is: "; 
     obj2.get_telephone(); 
     cout<< endl; 
    } 
}; 
void main() 
{ 

emp.obj; 
    cout << "Enter Name of employee " << endl; 
    cin >> nameInput; 
    cout << "-----------Enter address of employee----------- "<<endl; 
    cout << "Enter house: "; 
    cin >> emp.obj.m.houseno; //passing parameters to the struct 
    cout << "Enter colony : "; 
    cin >> emp.obj.m.colony; 
    cout << "Enter city: "; 
    cin >> emp.obj.m.city; 
    cout << "Enter telephone of employee: "; 
    cin >> telephoneInput; 

    emp.employee_name(nameInput); 
    emp.obj2.set_telephone(telephoneInput); 
    cout << "-------------Employee's Details are as follows------------ " << endl; 
    emp.show_emplyeeDetail(); 
} 
+6

你有問題嗎? – 2017-07-06 11:00:33

+0

您需要閱讀[良好的C++書](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) –

+0

'class address {private:public:'A whole新的冗長級別。替換這個'struct address {' –

回答

0

你的員工「是」的地址和電話號碼 - 這是多重繼承

class employee :public address, public telephoneNo 

在主,您可以訪問的公共字段和兩個基地的方法歸類任何僱員,例如

employee employee1; 
employee1.get_address(); 

另一方面,員工「有」地址和電話號碼 - 這是組成。

employee1.obj.get_address(); 

請注意,您的員工的兩個地址和電話號碼是嚴格分開的,可能(會)包含不同的內容。

但最好的建議是從一本好的C++初學者書開始。