简体   繁体   English

多重继承:相同的变量名称

[英]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::wordA::wordDerived之外你可以像这样访问它们(如果你改变它们对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::varB::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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM