简体   繁体   English

C ++类多重继承错误

[英]C++ class multiple inheritance error

I have been working on multiple inheritance. 我一直致力于多重继承。 I have made a program but it keeps giving me an error such as Human::getInfo is ambiguous. 我已经制作了一个程序,但它一直给我一个错误,比如Human :: getInfo是不明确的。 How do I solve the problem here is my code 我如何解决这个问题是我的代码

#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;
}

Also feel free to make changes in my code and would be even better if your could point out my mistake using my code. 也可以随意更改我的代码,如果您可以使用我的代码指出我的错误,那就更好了。

Your design is rather questionable, but the particular ambiguity arises because Human inherits from both Woman and Man , but Woman already inherits from Man . 你的设计是相当可疑的,但是出现了特殊的歧义,因为Human继承了WomanMan ,但Woman已经继承了Man

So Human has two getinfo() functions in it - Human::Man::getinfo() and Human::Woman::Man::getinfo() . 因此Human有两个getinfo()函数 - Human::Man::getinfo()Human::Woman::Man::getinfo() Unless you tell the compiler which one to use it doesn't know, and thus reports an error. 除非你告诉编译器哪一个使用它不知道,因此报告错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM