[英]c++: How do you access base class calls in multiple/multilevel inheritance from within the class?
This is the simplified code: 这是简化的代码:
class a
{
public:
void func( void )
{
//Want to call this
}
int avar;
};
class b : public a
{
public:
void func( void )
{
}
};
class c : public a
{
public:
void func( void )
{
}
};
class d : public b, public c
{
public:
void d1()
{
//b::a::avar;
//c::a::avar;
//b::a::func();
//c::a::func();
}
};
How do you properly qualify a call to access the members of both instances of the subclass a, the things I've tried leads to a 'a is an ambiguous base of d' error. 您如何正确地限定访问子类a的两个实例的成员的调用,我尝试过的事情导致出现“ a是d的歧义”错误。 Same question if the hierarchy was one more class deep or if a class template was involved.
相同的问题是层次结构是否更深一层类或是否包含类模板。 I'm not looking for a virtual base.
我不是在寻找虚拟基地。
You can call the immediate base class functions using the explicit calls. 您可以使用显式调用来调用直接基类函数。
void d1()
{
b::func();
c::func();
}
You can call a::func
from b::func
similarly. 您可以类似地从
b::func
调用a::func
。
class b : public a
{
public:
void func( void )
{
a::func();
}
};
If you also want to access the member a::var
and call a::func
directly from d::d1
, you can use: 如果您还想访问成员
a::var
并直接从d::d1
调用a::func
,则可以使用:
void d1()
{
b* bPtr = this;
bPtr->avar; // Access the avar from the b side of the inheritance.
bPtr->a::func(); // Call a::func() from the b side of the inheritance
c* cPtr = this;
cPtr->avar; // Access the avar from the c side of the inheritance.
cPtr->a::func(); // Call a::func() from the c side of the inheritance
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.