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?
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!!";
}
};
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.
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.
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