不能被繼承的類、不能被拷貝的類、只能定義一個對象的類
不能被繼承的類
將構(gòu)造函數(shù)和析構(gòu)函數(shù)定義為私有的,這樣派生類在構(gòu)造基類子對象時就不能調(diào)用基類私有的構(gòu)造函數(shù)。
class T
{
private:
T() {}
~T() {}
public:
static T* create()
{
return new T();
}
static T* release(T*& p)
{
delete p;
p = 0;
}
};
見構(gòu)造函數(shù)和析構(gòu)函數(shù)聲明為 private ,也限制了本身的對象創(chuàng)建。利用靜態(tài)成員函數(shù)來創(chuàng)建創(chuàng)建和釋放對象。
這種方式只能在堆上創(chuàng)建對象。
如果還想在棧上創(chuàng)建對象,利用友元機(jī)制,聲明友元類,可以調(diào)用友元類的 private 構(gòu)造函數(shù)和析構(gòu)函數(shù),但是友元關(guān)系不能被繼承。其中一個友元類 virtual 繼承自含有 private 構(gòu)造函數(shù)和析構(gòu)函數(shù)的被友元類。
不能拷貝的類
拷貝意味著拷貝構(gòu)造函數(shù)和復(fù)制運(yùn)算符,將拷貝構(gòu)造函數(shù)和賦值運(yùn)算符聲明為 protected 的,并且不需要實(shí)現(xiàn)。
class T
{
protected:
T(const T& rhs);
T& operator = (const T& rhs);
};
只能聲明一個對象的類
即是單例模式
將構(gòu)造函數(shù)聲明為 private 以防在棧上隨意定義對象
定義一個 static 的本類型指針,只是指向唯一的一個對象
定義一個 static 成員函數(shù),用于獲得指向唯一的那個對象的指針
class T
{
private:
T() {}
~T() {}
static T* pt;
public:
static T* getInstance()
{
if (pt == 0)
{
pt = new T();
}
return pt;
}
};
T* T::pt = 0;
http://www.shnenglu.com/jake1036/archive/2011/05/21/146870.html
http://blog.csdn.net/xkyx_cn/article/details/2245038
http://www.cublog.cn/u3/112083/showart_2237163.html
http://blog.csdn.net/ericming200409/article/details/5975874
http://blog.csdn.net/wulibin136/article/details/6347215
http://www.shnenglu.com/unixfy/archive/2011/04/29/145340.html
posted on 2011-07-23 21:48
unixfy 閱讀(746)
評論(0) 編輯 收藏 引用