【发布时间】:2018-07-11 06:06:41
【问题描述】:
我没有为我的类提供任何自定义构造函数,我所做的只是禁用了复制构造函数:
private:
MyClass(const MyClass& other) = delete; // disable copy ctor
现在,当我尝试在堆栈上创建此类的实例时
MyClass myInstance;
我收到如下编译错误:
main.cpp:16:16: error: no matching function for call to ‘MyClass::MyClass()’
好像我无意中禁用了默认构造函数?或者可能复制构造函数在那里被调用,我只是不知道如何。
这是一个例子
class MyClass {
public:
int someField;
private:
MyClass(const MyClass& other) = delete; // disable copy ctor
MyClass& operator=(MyClass other) = delete; // disable assignment
};
还有错误
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -MMD -MP -MF"proj/main.d" -MT"pitch/main.o" -o "proj/main.o" "../proj/main.cpp"
../proj/main.cpp: In function ‘int main()’:
../proj/main.cpp:17:10: error: no matching function for call to ‘MyClass::MyClass()’
MyClass ins;
【问题讨论】:
-
声明构造函数会禁用默认构造函数。从未测试过复制构造函数是否也会发生这种情况,但看起来像。
-
添加一个
MyClass () = default;应该可以解决它。 -
默认构造函数是默认创建的除非您决定创建或删除任何其他构造函数,那么您必须明确说明要保留哪个构造函数
-
因为规则5。如果你需要手动定义一个复制构造函数,编译器生成的默认构造函数很可能是错误的,因此不会生成。其他 5 个特殊成员函数基本相同。
标签: c++ oop constructor