继承错误的构造函数调用 [英] Inheritance wrong call of constructors

查看:126
本文介绍了继承错误的构造函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了这个钻石的继承:

  class Object {
private:
int id ;字符串名称;
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;};
};


类操作: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) ,t2){active = a;};
};

前三个类都可以正常工作,但是当我尝试创建一个ActionButton类型的对象,而不是用我写的参数调用构造函数,它是从类Object调用默认的。所以每个ButtonAction对象都有一个空字符串,id是一个随机值。我的代码有什么问题,我如何使它正常工作?

解决方案

虚拟基础直接构造函数 c> $ c>的构造函数,所以默认构造函数为您调用。


I'm implemeting this diamond inheritance:

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;};
};

Everything works fine about the first three classes, but when I try to create an object of the type ActionButton, instead of calling the constructor with the parameters I wrote, it is calling the default one from the class Object. So every ButtonAction object has name an empty string and id a random value. What's wrong with my code and how can i make it work properly?

解决方案

Virtual bases are constructed directly by the constructor of the most derived class.

Your ActionButton constructor doesn't explicitly call Object's constructor, so the default constructor is called for you.

这篇关于继承错误的构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆