不能被继承的类(私有构造函数) 代码(C++)
本文地址: http://blog.csdn.net/caroline_wendy
题目: 用C++设计一个不能被继承的类.
可以使用私有构造函数, 并提供静态成员函数, 返回和删除类的实例.
则只能在堆上创建实例, 不能在栈上创建.
代码:
/* * main.cpp * * Created on: 2014.7.13 * Author: Spike */ #include <iostream> #include <list> using namespace std; class SealedClass { public: static SealedClass* GetInstance() { return new SealedClass(); } static void DeleteInstance(SealedClass* pInstance) { delete pInstance; } private: SealedClass() {cout << "Constructor" << endl;} ~SealedClass() {cout << "Destructor" << endl;} }; int main(void) { SealedClass* s = SealedClass::GetInstance(); SealedClass::DeleteInstance(s); return 0; }
输出:
Constructor Destructor