访问派生类的各个类,派生自两个相同的基类

时间:2013-04-02 13:07:24

标签: c++ multiple-inheritance diamond-problem

我有一个名为Number基类。课程OneTwo来自Number。 现在我定义另一个类Three,我需要从多继承中访问各个基类:


class Number{
  protected:
     int val;
  public:
    Number(){
        val=0;
    }
    void Add(Number n){//Receives another Number class instance and add the value
        val+=n.val;
    }
};

//class One derived from Number
class One:public Number{
  public:
     One(){
          cal=1;
     }
};

//class two derived from Number
class Two:public Number{
  public:
     Two(){
          val=2;
     }
};

class Three:public One,public Two{
  public:
     Three(){
          Two::Add(One);//--How can i pass instance of class One Here
     }
};

我尝试了One :: Number和Two :: Number,但没有用。

4 个答案:

答案 0 :(得分:0)

有一些问题,首先val是私有的,因此需要protected。接下来您有一个diamond of death,因此virtual publicOne需要Two。您还尝试使用Add来呼叫type,但每个班级都需要instance

class Number{
protected:
     int val;
public:
    Number(){
        val=0;
    }
    void Add(Number& n){//Receives another Number class instance and add the value
        val+=n.val;
    }
};

//class One derived from Number
class One:virtual public Number{
public:
     One(){
          val=1;
    }
};

//class two derived from Number
class Two:virtual public Number{
public:
     Two(){
          val=2;
     }
};

class Three: public  One,  public  Two{
public:
     Three()
     {
           Two t1 ;
           Add(t1 );//--How can i pass instance of class Two Here
     }
};

可以说使用protected数据很糟糕,但它取决于on your case,但要完成它还可以选择保留val private数据成员和使用protected constructor,看起来像这样:

class Number{
private:
     int val;
protected:
   Number( int n ) : val(n) {} 
public:
    Number(){
        val=0;
    }
    void Add(Number& n){//Receives another Number class instance and add the value
        val+=n.val;
    }
};

class One: virtual public Number{
public:
     One() : Number( 1 ) {

     }
};

class Two: virtual public Number{
public:
     Two() : Number(2) {
     }
};  

答案 1 :(得分:-1)

您需要创建相应类型的对象。

class Three : public One, public Two
{
public:
     Three()
     {
          Add(One());
          Add(Two());
     }
};

但我不明白为什么你需要MI。继承数字就足够了。

答案 2 :(得分:-1)

这应该有效:

Two::Add(*(One*)this);

答案 3 :(得分:-1)

问题不仅仅是语法。但你究竟想做什么?

你可以。但One的实例在哪里宣布?你必须先申报。记住Two::Add(One);不是声明而是呼叫声明。

你在做什么相当于让我们说

process_number(One);

进程号是一个函数。