[英]Multiple Inheritance: same variable name
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
? 如何在
Derived
影响变量word
的可访问性? 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: 您可以使用
using
关键字告诉编译器使用哪个版本:
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
. 这告诉编译器
Derived
类有一个受保护的成员word
,它将是A::word
的别名。 Then whenever you use the unqualified identifier word
in the Derived
class, it will mean A::word
. 然后,无论何时在
Derived
类中使用非限定标识符word
,它都将表示A::word
。 If you want to use B::word
you have to fully qualify the scope. 如果你想使用
B::word
你必须完全限定范围。
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
类有两个变量, B::word
和A::word
在Derived
之外你可以像这样访问它们(如果你改变它们对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. 尝试访问
c.word
将导致错误 ,因为没有名称为word
字段,但只有A :: word和B :: word。
Inside Derived
they behave like regular fields, again, with the names A::var
and B::var
also mentioned in other answers. 在
Derived
它们的行为类似于常规字段,同样在其他答案中也提到了名称A::var
和B::var
。
When accessing word
in the class of Derived
, you had to declare 当访问
Derived
类中的word
时,您必须声明
class Derived: public A, public B
{
Derived()
{
A::word = X;
//or
B::word = x;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.