我有两种机器和人类,它们实际上是从原子继承的。现在,我编写了一个名为“ 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;
}
但是,由于const成员“ transformium”,CXX编译器要求Machine初始化Atom。
error: constructor for 'Machine' must explicitly initialize the base class 'Atom' which does not have a default constructor
正如编译器错误提示的那样,您必须Atom
在的构造函数中显式初始化基类Machine
。
这样做的原因是您可以创建的实例Machine
。对于这样的对象,必须有一种方法来正确初始化的Atom
部分Machine
。
更新资料
Atom
被初始化的不同,这取决于你是否创建一个实例Human
,Machine
或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;
}
输出:
来到Atom :: Atom() ------------------ 来到Atom :: Atom() ------------------ 来到Atom :: Atom()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句