一个类,当只有数据成员时,C98的编译器会隐式的产生四个默认函数:
缺省构造函数
析构函数
拷贝构造函数
如果类设计者自己实现了有参构造函数,同时又不想抛弃无参默认构造函数,则可以使用=default关键字来显示的指定编译器自己生成默认构造函数
=default
class CString{char* _str;public:CString() = default;//构造函数CString(const char* pstr) :_str(nullptr){UpdateString(pstr);}//析构函数~CString(){if (_str)free(_str);}public:void UpdateString(const char* pstr) throw(){if (pstr == nullptr)return;if (_str)free(_str);_str = (char*)malloc(strlen(pstr) + 1);strcpy(_str, pstr);}public:char* GetStr()const throw(){return _str;}};int main(){//auto str = std::make_unique<CString>("123");//printf(str->GetStr());auto str = std::make_unique<CString>(); //编译报错,没有合适的默认构造函数可用 需要指定=default来生成默认构造函数system("pause");return 0;}
