use*_*200 3 c++ overloading multiple-inheritance ambiguous name-lookup
基本上,我想让多个成员函数具有相同的名称,但签名不同,并散布在多个基类中。
例:
#include <iostream>
struct A
{
void print(int) { std::cout << "Got an int!" << std::endl; }
};
struct B
{
void print(double) { std::cout << "Got a double!" << std::endl; }
};
struct C : A, B {};
int main()
{
C c;
c.print((int)0);
return 0;
};
Run Code Online (Sandbox Code Playgroud)
但是我在clang上收到此错误:
main.cpp:18:7: error: member 'print' found in multiple base classes of different types
c.print((int)0);
^
main.cpp:5:10: note: member found by ambiguous name lookup
void print(int) { std::cout << "Got an int!" << std::endl; }
^
main.cpp:10:10: note: member found by ambiguous name lookup
void print(double) { std::cout << "Got a double!" << std::endl; }
Run Code Online (Sandbox Code Playgroud)
为什么模棱两可?即使使用不同数量的参数,我也会遇到相同的错误。
是否有任何变通办法以获得类似的行为?
using在派生类中使用声明-它可以解决您的问题。这会使两个过载可见和 可以参加决议。
struct C : A, B {
using A::print;
using B::print;
};
Run Code Online (Sandbox Code Playgroud)
要回答为什么这是模棱两可的:实际上,这与可见性无关,而是与由于未在同一范围内定义而无法参与过载解析有关。该using声明将这些方法拉入范围C,因此它们都成为有效的重载解决方案选项。
感谢@Pete Becker参与了这个答案,并非常感谢您创建本段。
| 归档时间: |
|
| 查看次数: |
791 次 |
| 最近记录: |