【问题标题】:how do I allocate a pointer to a class with multiple inheritance如何分配指向具有多重继承的类的指针
【发布时间】:2015-05-31 22:59:07
【问题描述】:

假设我有:

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 的指针?

【问题讨论】:

    标签: c++ class pointers multiple-inheritance


    【解决方案1】:

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

    但是,您尝试在没有任何参数的情况下构造 Refree - 它隐式地尝试在没有任何参数的情况下构造其所有基础。那是不可能的。抛开将某个东西同时设为HumanComputer 是否有意义,至少您必须执行以下操作:

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

    更有可能的是,您想提供一个带有一个或两个名称的构造函数,例如:

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

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 2017-07-30
      • 2016-03-03
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      相关资源
      最近更新 更多