gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:20:24 25 4
gpt4 key购买 nike

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

例子:

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

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

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

最佳答案

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

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

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

感谢 @Pete Becker 参与了这个回答并几乎创作了这个段落。

关于c++ - 在多个基类之间重载成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com