我如何分配一个指针到一个类的多重继承

how do I allocate a pointer to a class with multiple inheritance

本文关键字:一个 多重继承 指针 何分配 分配      更新时间:2023-10-16

假设我有:

class Human {
    string choice;
public:
    Human(string);
};
class Computer {
    string compChoice;
public:
    Computer(string);
};
class Refree : public Human, public Computer {
public:
    string FindWinner();
};
int main() {
    Human* H1 = new Human("name");
    Computer* C1 = new Computer("AI");
    Refree* R1 = new Refree();
}

使用

编译失败
 In function 'int main()':
error: use of deleted function 'Refree::Refree()'
note: 'Refree::Refree()' is implicitly deleted because the default definition  would be ill-formed:
error: no matching function for call to 'Human::Human()'
note: candidates are:
note: Human::Human(std::string)
note:   candidate expects 1 argument, 0 provided

为什么这个失败,我如何构造一个指向Refree的指针?

由于HumanComputer有用户声明的带实参的构造函数,它们的默认构造函数被隐式删除。为了构造它们,你需要给它们一个参数。

然而,您试图在没有任何参数的情况下构建Refree -它隐含地试图在没有任何参数的情况下构建其所有基。那是不可能的。抛开HumanComputer是否有意义不谈,至少你必须做这样的事情:

Refree()
: Human("human name")
, Computer("computer name")
{ }

更可能的情况是,您希望提供一个接受一个或两个名称的构造函数,例如:

Refree(const std::string& human, const std::string& computer)
: Human(human)
, Computer(computer)
{ }