标签:
bak 类是一个单例类,只能通过静态 getInstance 接口获取bak * 指针。
将构造函数设置为私有的,可以阻止在类外进行创建对象。
class bak { private: bak(){} public: ~bak(){} static bak * getInstance() { if(m_pBak == NULL){ m_pBak = new bak; } return m_pBak; } public: void show() { cout<<" show "<<endl; } private: static bak * m_pBak; }; bak * bak::m_pBak = NULL; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; bak * pB = bak::getInstance(); pB->show(); system("pause"); return 0; }
构造函数设置为私有可以防止类外创建对象,那么析构函数能不能设置私有? 可以
析构函数设置为私有,可以防止在类外 删除对象
class bak { private: bak(){} ~bak(){} public: static bak * getInstance() { if(m_pBak == NULL){ m_pBak = new bak; } return m_pBak; } public: void show() { cout<<" show "<<endl; } private: static bak * m_pBak; }; bak * bak::m_pBak = NULL; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; bak * pB = bak::getInstance(); pB->show(); delete pB; system("pause"); return 0; }
结果直接报错
标签:
原文地址:http://www.cnblogs.com/techdreaming/p/5693394.html