C++中的 =default
参考:链接
每当我们声明一个有参构造函数时,编译器就不会创建默认构造函数。如下代码就会发生错误:
// use of defaulted functions
#include <iostream>
using namespace std;
class A {
public:
// A user-defined
A(int x){
cout << "This is a parameterized constructor";
}
// Using the default specifier to instruct
// the compiler to create the default implementation of the constructor.
// A() = default;
};
int main(){
A a; //call A()
A x(1); //call A(int x)
cout<<endl;
return 0;
}
在这种情况下,我们可以使用default说明符来创建默认说明符。以下代码演示了如何创建:
// use of defaulted functions
#include <iostream>
using namespace std;
class A {
public:
// A user-defined
A(int x){
cout << "This is a parameterized constructor";
}
// Using the default specifier to instruct
// the compiler to create the default implementation of the constructor.
A() = default;
};
int main(){
A a; //call A()
A x(1); //call A(int x)
cout<<endl;
return 0;
}