一个类,当只有数据成员时,C98的编译器会隐式的产生四个默认函数:
缺省构造函数
析构函数
拷贝构造函数

如果类设计者自己实现了有参构造函数,同时又不想抛弃无参默认构造函数,则可以使用=default关键字来显示的指定编译器自己生成默认构造函数

=default

  1. class CString
  2. {
  3. char* _str;
  4. public:
  5. CString() = default;
  6. //构造函数
  7. CString(const char* pstr) :_str(nullptr)
  8. {
  9. UpdateString(pstr);
  10. }
  11. //析构函数
  12. ~CString()
  13. {
  14. if (_str)
  15. free(_str);
  16. }
  17. public:
  18. void UpdateString(const char* pstr) throw()
  19. {
  20. if (pstr == nullptr)
  21. return;
  22. if (_str)
  23. free(_str);
  24. _str = (char*)malloc(strlen(pstr) + 1);
  25. strcpy(_str, pstr);
  26. }
  27. public:
  28. char* GetStr()const throw()
  29. {
  30. return _str;
  31. }
  32. };
  33. int main()
  34. {
  35. //auto str = std::make_unique<CString>("123");
  36. //printf(str->GetStr());
  37. auto str = std::make_unique<CString>(); //编译报错,没有合适的默认构造函数可用 需要指定=default来生成默认构造函数
  38. system("pause");
  39. return 0;
  40. }

=delete