构造函数和析构函数的私有化

    技术2022-07-10  77

    //例程:构造函数和析构函数的私有化 #include <iostream> #include <cstdio> #include <cstring> #include <cmath> using namespace std; class Human { public: void test() { printf("Human--------\n"); } static Human* create(){ return new Human; } void destory(){ delete this; } private: Human(){ printf("constructor is called!\n"); } ~Human(){ printf("destrcutor is called!\n"); } }; int main(int argc, char* argv[]) { Human *hp = Human::create(); //构造函数被私有化,只能用公有函数create在类内分配内存 hp->destory(); //delete hp; //析构函数被私有化,无法用delete函数调用,只能用拥有函数destory在类内释放内存 return 0; }
    Processed: 0.008, SQL: 9