繁体   English   中英

C++多重继承函数调用歧义

[英]C++ multiple inheritance function call ambiguity

我有一个与 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()

我现在不知道用例但是..仍然!

a.base1::start();

a.base2::start();

或者如果你想特别使用一个

class derived:public base1,public base2
{
public:
    using base1::start;
};

当然!

a.base1::start();

要么

a.base2::start();

除了上面的答案,如果我们是在非虚拟继承的情况下:

你可以:

  1. 使用static_cast<base1*>(a).start()

要么

  1. 在派生中覆盖 start()

顺便说一句 - 请注意可能出现的钻石问题。 在这种情况下,您可能想要使用虚拟。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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