c++ - 在多个基类之间重载成员函数
问题描述
基本上我希望有多个具有相同名称但签名不同的成员函数,分布在多个基类中。
例子:
#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参与此答案并几乎创建了本段。
推荐阅读
- android - 如何使用 Firebase SDK 向 Google Analytics 报告在移动应用中进行但离线支付的购买
- reactjs - Web-worker 问题:未捕获的 DOMException:无法在“Worker”上执行“postMessage”
- github-actions - github操作,构建docker镜像,根据分支名称设置名称
- c - fprintf 和 stdout 的整体效率
- amazon-web-services - aws 胶水`ImportError:无法导入名称'S3ArnParamHandler'`
- react-native - React Native - ExpoPixi:非法调用
- php - 使用 symfony 命令发送邮件时嵌入图像不可读
- typescript - TypeScript:将输入类型 T 映射到树状类型
- amazon-web-services - 获取“InvalidAccessKeyId:您提供的 AWS 访问密钥 ID 在我们的记录中不存在。” 更新放大用户 IAM 密钥后
- powershell - PowerShell中有输入输出功能吗?