首页 > 解决方案 > 在多个基类之间重载成员函数

问题描述

基本上我希望有多个具有相同名称但签名不同的成员函数,分布在多个基类中。

例子:

#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;
};

但是我在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; }

为什么会模棱两可?即使使用不同数量的参数,我也会得到相同的错误。

是否有任何解决方法来获得类似的行为?

标签: c++overloadingmultiple-inheritanceambiguousname-lookup

解决方案


using在派生类中使用声明 - 它会解决您的问题。它使两个重载可见和可以参与决议。

struct C : A, B {
    using A::print;
    using B::print;
};

回答为什么这是模棱两可的:它实际上不是关于可见性,而是关于由于没有在同一范围内定义而无法参与重载决议。using声明将这些方法拉入范围C,因此它们都成为有效的重载解决方案选项。

感谢@Pete Becker参与此答案并几乎创建了本段。


推荐阅读