构造函数的继承错误调用
Inheritance wrong call of constructors
我正在实施钻石继承:
class Object {
private:
int id; string name;
public:
Object(){};
Object(int i, string n){name = n; id = i;};
};
class Button: virtual public Object {
private:
string type1;
int x_coord, y_coord;
public:
Button():Object(){};
Button(int i, string n, string ty, int x, int y):Object(i, n){
type = ty;
x_coord = x;
y_coord = y;};
};
class Action: virtual public Object {
private:
string type2;
public:
Action():Object(){};
Action(int i, string n, string t):Object(i, n){ type2 = t;};
};
class ActionButton: public Button, public Action{
private:
bool active;
public:
ActionButton():Buton(), Action(){};
ActionButton(int i, string n, string t1, int x, int y, string t2, bool a):
Button(i, n, t1, x, y), Action(i, n, t2) {active = a;};
};
前三个 class 一切正常,但是当我尝试创建 ActionButton 类型的对象时,它没有使用我编写的参数调用构造函数,而是从class 对象。所以每个 ButtonAction 对象都有一个空字符串的名称和一个随机值。我的代码有什么问题,我怎样才能让它正常工作?
虚基由最派生的构造函数直接构造class。
您的 ActionButton
构造函数没有显式调用 Object
的构造函数,因此为您调用了默认构造函数。
我正在实施钻石继承:
class Object {
private:
int id; string name;
public:
Object(){};
Object(int i, string n){name = n; id = i;};
};
class Button: virtual public Object {
private:
string type1;
int x_coord, y_coord;
public:
Button():Object(){};
Button(int i, string n, string ty, int x, int y):Object(i, n){
type = ty;
x_coord = x;
y_coord = y;};
};
class Action: virtual public Object {
private:
string type2;
public:
Action():Object(){};
Action(int i, string n, string t):Object(i, n){ type2 = t;};
};
class ActionButton: public Button, public Action{
private:
bool active;
public:
ActionButton():Buton(), Action(){};
ActionButton(int i, string n, string t1, int x, int y, string t2, bool a):
Button(i, n, t1, x, y), Action(i, n, t2) {active = a;};
};
前三个 class 一切正常,但是当我尝试创建 ActionButton 类型的对象时,它没有使用我编写的参数调用构造函数,而是从class 对象。所以每个 ButtonAction 对象都有一个空字符串的名称和一个随机值。我的代码有什么问题,我怎样才能让它正常工作?
虚基由最派生的构造函数直接构造class。
您的 ActionButton
构造函数没有显式调用 Object
的构造函数,因此为您调用了默认构造函数。