#includeclass Base{ public: static Base CreateObject(){ return Base(); } private: Base(){} }; void Test() { //Base* p = new Base; //Base b; // 虽然构造函数私有,但由编译器提供的赋值构造函数可以进行类外赋值 // 仍然无法对象只能申请在堆空间中 Base b = Base::CreateObject(); Base b1(b);//拷贝 } class Base1{ public: void Destroy() const{ if (this != nullptr) delete this; } private: ~Base1(){} }; // 虽然析构函数设置为private,但妨碍了继承和内含场景 void Test1(){ // Base1 b;// error, 析构函数私有 // 私有new在堆空间申请 Base1 *p = new Base1(); // delete p; 析构函数是私有的 p->Destroy(); // ok } class Derived: public Base1{ }; class Contact{ private: Base1 b; }; class Contact1{ public: Contact1(): p(new Base1){} private: Base1* p; }; void Test2(){ // Derived d;// error, 父类析构函数是私有的 // Contact c;// error ,Base1析构函数是私有的 // 克服子类继承父类时无法创建对象,只需要将父类析构函数private改为protected // 克服其他类内含析构函数为私有的类对象,则只需要在内含类中将类对象改为类对象指针 Contact1 c;// ok } int main() { Test(); return 0; }



