当我声明和定义一个没有参数的构造函数和一个带参数的构造函数时,为什么编译器会抱怨?

时间:2015-08-18 03:23:37

标签: c++ constructor overloading

我在C ++中有这段代码:

@implementation FTGCollectionView

- (void)layoutSubviews {
    [super layoutSubviews];
    //[self layoutIfNeeded]; // Should not call as it cause collection view to not scroll
}

@end

但是Windows 7 64位上的编译器(MinGW 4.8.1)抱怨重载'Object()'的模糊不清:

#include <iostream>

class Object
{
    public:
        Object();
        Object(int someValue = 0);

    private:
        int value;
};

Object::Object()
{
    std::cout << "No argument constructor" << std::endl;
    value = 0;
}

Object::Object(int someValue)
{
    std::cout << "Argument constructor" << std::endl;
    value = someValue
}

int main()
{
    Object obj1;     // should call Object() (according to me)
    Object obj2(5);  // should call Object(int) (according to me)
}

理想情况下,我希望获得此输出:

defaultConstructorTest.cpp: In function 'int main()':
defaultConstructorTest.cpp:27:9: error: call of overloaded 'Object()' is  ambiguous
  Object obj1;
         ^
defaultConstructorTest.cpp:27:9: note: candidates are:
defaultConstructorTest.cpp:19:1: note: Object::Object(int)
Object::Object(int someValue)
^
defaultConstructorTest.cpp:13:1: note: Object::Object()
Object::Object()
^

1 个答案:

答案 0 :(得分:3)

这是因为呼吁

sudo cp -rp /home/source /tmp/dest

含糊不清。因为第二个构造函数有一个默认参数,这使得它成为对象默认构造的足够好的竞争者。