2014-02-08 64 views
0

我一直在研究多重繼承。我製作了一個程序,但它一直給我一個錯誤,比如Human :: getInfo不明確。我該如何解決這個問題 這裏是我的代碼C++類多重繼承錯誤

#include <iostream> 
#include <string> 
using namespace std; 

class Man{ 
protected: 
    std::string name; 
public: 
    void getInfo(string hName){ 
     name = hName; 
    } 
    void showInfo(){ 
     std::cout << "Your name is: " << name << std::endl; 
     std::cout << "And you are a MAN" << std::endl; 
    } 
}; 

class Women:public Man{ 
public: 
    Women(){} 
    void Women_showInfo(){ 
     std::cout << "Your name is: " << name << std::endl; 
     std::cout << "And you are a Women" << std::endl; 
    } 
}; 

class Human:public Women, public Man{ 
public: 
    Human(){} 
}; 
int main(){ 
    //local variables 
    string choice; 
    string name; 
    //class object 
    Human person; 
    //user interface 
    cout << "What your name: " ; 
    cin >> name; 
    cout << "Are you a [boy/girl]: "; 
    cin >> choice; 
    //saving name 
    person.getInfo(name); //ambiguous 
    //if handler 
    if (choice == "boy"){ 
     person.showInfo(); //ambiguous 
    }else if(choice == "girl"){ 
     person.Women_showInfo(); //works fine no error 
    } 
    system("pause"); 
    return 0; 
} 

也放心大膽地在我的代碼的變化和甚至會更好,如果你可以使用我的代碼,指出我的錯誤。

回答

2

你的設計是相當有問題,但具體歧義的產生是因爲來自WomanMan,但WomanHuman繼承已從Man繼承。

所以Human有兩個getinfo()函數 - Human::Man::getinfo()Human::Woman::Man::getinfo()。除非你告訴編譯器哪一個使用它不知道,並因此報告錯誤。

+0

通過添加到人類的聲明如下:'使用Man :: getInfo();' – SHR

+0

如果你不介意使用代碼給我看,因爲它很難理解@Jonathan Potter – user3264250

+0

代替'person .getInfo(name);''你會做'person.man :::getinfo(name);'或'person.Woman :: Man :: getinfo(name);'。 –