代码之家  ›  专栏  ›  技术社区  ›  user3762200

在多个基类之间重载成员函数

  •  2
  • user3762200  · 技术社区  · 7 年前

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

    例子:

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

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

    有什么办法可以让你做出类似的行为吗?

    1 回复  |  直到 7 年前
        1
  •  6
  •   Fureeish    6 年前

    使用 using 派生类中的声明-它将修复您的问题。它使两个重载 可见和 参与决议是可行的。

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

    要回答为什么这是模棱两可的:实际上不是关于 可见度 ,但关于无法 参与 由于未在同一范围内定义而导致的重载解决方案。这个 使用 声明在 C 范围,因此它们都成为有效的重载解析选项。

    多亏了 @皮特·贝克尔 因为你参与了这个答案,并且创造了这个段落。