c++ - 为什么编译器会抛出一个错误,说重载的构造函数不明确?
问题描述
示例类如下所示:
class Example
{
public:
Example(): x_(0) {} // problematic constructor
Example(int x = 1): x_(x){} // not problematic constructor
int getX() { return x_; }
private:
int x_;
};
在 main 中测试示例:
int main()
{
// problem with this constructor
Example example1;
auto x1 = example1.getX();
// no problem with this constructor
Example example2(500);
auto x2 = example2.getX();
}
已解决的问题:
通过删除第二个构造函数中的默认参数值来消除构造函数的歧义。构造函数如下所示:
Example(): x_(0) {}
Example(int x): x_(x){}
这不会违反导致歧义的 cpp 构造函数重载规则。
解决方案
参数的默认值使对默认构造函数的调用不明确。这将调用哪个函数,第一个构造函数,还是第二个?
Example example1 = Example(); // equivalent of Example example1;
唯一的解决办法是不要形成这样的声明。默认所有参数的构造函数等于没有参数的构造函数。
class Example
{
public:
Example(int x = 0): x_(x){} // same as default constructor
int getX() { return x_; }
private:
int x_;
};
推荐阅读
- python - 海龟图形:如何实现暂停功能?
- udp - 一台机器上的两个客户端之间的 UDP 打孔
- reactjs - 从辅助源更新反应组件的正确方法
- android - Kotlin 接口无法实例化!接口名称:kotlinx.coroutines.Deferred
- c++ - 带有作为类的一部分的向量的函数不起作用并且没有编译器错误
- amazon-web-services - 性能问题 - 基于 Lambda 的 API - 直接托管在 AWS 上与通过 Netlify 函数托管
- ios - 在没有网络的情况下在软件和应用程序之间连接在线网络服务器
- reactjs - Redux CombineReducers 在调度每个动作后返回 defaultState
- python - 硒。x 轮播中数据的路径
- php - PHP - 客户选择 X 数量 - 想要从库存和电子邮件中获取 X 数量