gpt4 book ai didi

c++ - 没有显式初始化父类的虚拟继承

转载 作者:搜寻专家 更新时间:2023-10-31 01:43:24 27 4
gpt4 key购买 nike

我有两个类 Machine 和 Human,它们实际上是从 atom 继承的。现在我编写了一个名为“Cyborg”的类,并希望从 Cyborg 初始化 Atom。代码是

#include <iostream>

using namespace std;

class Atom {
public:
Atom(size_t t): transformium(t) {};
private:
const size_t transformium;
};

class Human : public virtual Atom {
public:
Human(string name) : Atom(-1), name(name) {}
protected:
string name;
};

class Machine : public virtual Atom {
public:
Machine() {}
Machine(int id) : id(id) {}
protected:
int id;
};

class Cyborg : public Human, public Machine {
public:
Cyborg(string name, int id) : Atom(0), Human(name) {}
};

int main() {
Cyborg cyborg("robocup", 911);
return 0;
}

但是,由于常量成员“transformium”,CXX 编译器需要 Machine 来初始化 Atom。

error: constructor for 'Machine' must explicitly initialize the base class 'Atom' which does not have a default constructor

最佳答案

正如编译器错误提示的那样,您必须在 Machine 的构造函数中显式初始化基类 Atom

这样做的原因是您可以创建 Machine 的实例。对于这样的对象,必须有一种方法来正确初始化 MachineAtom 部分。

更新

Atom 的初始化方式不同,具体取决于您创建的是 HumanMachine 还是 Cyborg 的实例。这是您的代码的更新版本,其中包含一些解释。

#include <iostream>

using namespace std;

class Atom {
public:
Atom(size_t t): transformium(t) { std::cout << "Came to Atom::Atom()\n"; }
private:
const size_t transformium;
};

class Human : public virtual Atom {
public:
Human(string name) : Atom(-1), name(name) {}
// Atom(-1) is ignored when an instance of Cyborg is created
// but not when an instance of Human is created.
protected:
string name;
};

class Machine : public virtual Atom {
public:
Machine(int id) : id(id), Atom(-1) {}
// Atom(-1) is ignored when an instance of Cyborg is created
// but not when an instance of Machine is created.
protected:
int id;
};

class Cyborg : public Human, public Machine {
public:
Cyborg(string name, int id) : Atom(0), Human(name), Machine(id) {}
// Atom needs to be intialized here since it won't be initialized
// in either Human or Machine.
};

int main() {
Cyborg cyborg("robocup", 911); // Calls Atom::Atom() only once.
std::cout << "------------------\n";
Human human("robocup"); // Calls Atom::Atom() once.
std::cout << "------------------\n";
Machine machine(911); // Calls Atom::Atom() once.
return 0;
}

输出:

Came to Atom::Atom()------------------Came to Atom::Atom()------------------Came to Atom::Atom()

关于c++ - 没有显式初始化父类的虚拟继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225688/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com