Multiple Inheritance: same variable name

2020-02-13 07:04发布

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?

4条回答
戒情不戒烟
2楼-- · 2020-02-13 07:46

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楼-- · 2020-02-13 07:51

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楼-- · 2020-02-13 07:52

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!!";
    }
};
查看更多
男人必须洒脱
5楼-- · 2020-02-13 07:54

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;
    }
};
查看更多
登录 后发表回答