Multiple Inheritance: same variable name

淺唱寂寞╮ 提交于 2019-11-28 07:02:17

问题


class A
{
   protected:
    string word;
};

class B
{
   protected:
    string word;
};

class Derived: public A, public B
{

};

How would the accessibility of the variable word be affected in Derived? How would I resolve it?


回答1:


It will be ambiguous, and you'll get a compilation error saying that.

You'll need to use the right scope to use it:

 class Derived: public A, public B
{
    Derived()
    {
        A::word = "A!";
        B::word = "B!!";
    }
};



回答2:


You can use the using keyword to tell the compiler which version to use:

class Derived : public A, public B
{
protected:
    using A::word;
};

This tells the compiler that the Derived class has a protected member word, which will be an alias to A::word. Then whenever you use the unqualified identifier word in the Derived class, it will mean A::word. If you want to use B::word you have to fully qualify the scope.




回答3:


Your class Derived will have two variables, B::word and A::word Outside of Derived you can access them like this (if you change their access to public):

Derived c;
c.A::word = "hi";
c.B::word = "happy";

Attempting to access c.word will lead to an error, since there is no field with the name word, but only A::word and B::word.

Inside Derived they behave like regular fields, again, with the names A::var and B::var also mentioned in other answers.




回答4:


When accessing word in the class of Derived, you had to declare

class Derived: public A, public B
{
    Derived()
    {
       A::word = X;
       //or
       B::word = x;
    }
};


来源:https://stackoverflow.com/questions/19763903/multiple-inheritance-same-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!