当多个基类具有同名成员函数时,如何解决函数调用歧义?
我有一个与 C++ 多重继承相关的基本问题。如果我有如下所示的代码:
struct base1 {
void start() { cout << "Inside base1"; }
};
struct base2 {
void start() { cout << "Inside base2"; }
};
struct derived : base1, base2 { };
int main() {
derived a;
a.start();
}
会出现以下编译错误:
1>c:\mytest.cpp(41): error C2385: ambiguous access of 'start'
1> could be the 'start' in base 'base1'
1> or could be the 'start' in base 'base2'
是否无法使用派生类对象从特定基类调用函数 start()
?
我现在不知道用例但是..仍然!
I have a basic question related to multiple inheritance in C++. If I have a code as shown below:
struct base1 {
void start() { cout << "Inside base1"; }
};
struct base2 {
void start() { cout << "Inside base2"; }
};
struct derived : base1, base2 { };
int main() {
derived a;
a.start();
}
which gives the following compilation error:
1>c:\mytest.cpp(41): error C2385: ambiguous access of 'start'
1> could be the 'start' in base 'base1'
1> or could be the 'start' in base 'base2'
Is there no way to be able to call function start()
from a specific base class using a derived class object?
I don't know the use-case right now but.. still!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者如果你想专门使用一个
or if you want to use one specifically
当然!
或者
Sure!
or
除了上面的答案之外,如果我们处于非虚拟继承的情况:
您可以:
static_cast(a).start()
或
顺便说一句 - 请注意可能出现的钻石问题。在这种情况下,您可能需要使用虚拟。
In addition to the answers above, if we are in the case of NON-VIRTUAL inheritance:
you can:
static_cast<base1*>(a).start()
or
Btw - please note the diamond problem that can appear. In this case you might want to use virtual.