C++构造/析构函数
/* 此处代码示例C++类构造和析构的限定符使用 主要包括以下内容: + 禁止产生基类对象 + 单例 + 禁止堆上产生对象 + 禁止栈上产生对象 */ #pragma once #include <iostream> using namespace std; // 禁止使用拷贝构造函数和 operator= 赋值操作的宏 // 应该类的 private: 中使用 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) // 禁止产生基类对象 // - 限定基类构造和析构为protected class BaseFoo { public: virtual void Say() { cout << "Hello from BaseFoo" << endl; } protected: BaseFoo(){}; virtual ~BaseFoo(){}; private: DISALLOW_COPY_AND_ASSIGN(BaseFoo); }; class DerivedFoo : public BaseFoo { public: DerivedFoo(){}; virtual ~DerivedFoo(){}; public: virtual void Say() { cout << "Hello from DerivedFoo" << endl; } private: DISALLOW_COPY_AND_ASSIGN(DerivedFoo); }; // 单例 // - 限定构造和析构函数为private // - 提供一个静态接口获得实例 class SimpleSingleton { public: static SimpleSingleton& GetInstance() { static SimpleSingleton me; return me; } public: void Say() { cout << "Hello from SimpleSingleton" << endl; } private: SimpleSingleton(){}; ~SimpleSingleton(){}; private: DISALLOW_COPY_AND_ASSIGN(SimpleSingleton); }; // 禁止堆上产生对象 // - 重载new和delete且限定为private class OBJNotOnHeap { public: OBJNotOnHeap(){}; ~OBJNotOnHeap(){}; public: void Say() { cout << "Hello from OBJNotOnHeap" << endl; } protected: void* operator new(std::size_t); void operator delete(void*); private: DISALLOW_COPY_AND_ASSIGN(OBJNotOnHeap); }; // 禁止栈上产生对象 // - 限定构造与析构函数为private // - 提供两个静态接口模拟new和delete class OBJNotOnStack { public: static OBJNotOnStack* CreateInstance() { return new OBJNotOnStack; } static void DestoryInstance(OBJNotOnStack* pObj) { delete pObj; } public: void Say() { cout << "Hello from OBJNotOnHeap" << endl; } private: OBJNotOnStack(){}; ~OBJNotOnStack(){}; private: DISALLOW_COPY_AND_ASSIGN(OBJNotOnStack); }; //---------------------------------------------------- // 测试函数 void main() { //BaseFoo foo; // 编译不过 DerivedFoo foo2; BaseFoo* pFoo = new DerivedFoo; foo2.Say(); pFoo->Say(); delete (DerivedFoo*)pFoo; pFoo = NULL; //SimpleSingleton ss; // 编译不过 SimpleSingleton& singleton = SimpleSingleton::GetInstance(); singleton.Say(); //OBJNotOnHeap* p = new OBJNotOnHeap; // 编译不过 OBJNotOnHeap obj; obj.Say(); //OBJNotOnStack* p1 = new OBJNotOnStack; // 编译不过 //OBJNotOnStack obj2; // 编译不过 OBJNotOnStack* p2 = OBJNotOnStack::CreateInstance(); p2->Say(); //delete p2; // 编译不过 OBJNotOnStack::DestoryInstance(p2); p2 = NULL; }
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity. We had everything before us, we had nothing before us.
这是最好的时代,这是最坏的时代;这是智慧的年代,这是愚蠢的年代;这是信仰的时期,这是怀疑的时期;我们的前途拥有一切,我们的前途一无所有。
这是最好的时代,这是最坏的时代;这是智慧的年代,这是愚蠢的年代;这是信仰的时期,这是怀疑的时期;我们的前途拥有一切,我们的前途一无所有。