首页 > 解决方案 > 为什么编译器会抛出一个错误,说重载的构造函数不明确?

问题描述

示例类如下所示:

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 构造函数重载规则。

标签: c++

解决方案


参数的默认值使对默认构造函数的调用不明确。这将调用哪个函数,第一个构造函数,还是第二个?

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

推荐阅读