C++設計中的類模板和函數模板

一、補充static
static 函數沒有this pointor  它只能用來處理靜態數據
class Account
{
public:
static double m_rate;
static void set_rate(const double& x){m_data =x;}


};
double Account::m_rate=8.0;//靜態數據在外面一定要寫這個
int main()
{
Account::set_rate(5.0);
Account a;
a.set_rate(7.0);
}
二、把ctors放在private 
class A
{
public:
static A& getInstance(return a;);
setup(){}
private:
A();
A(const A& ths);
static A a;
};
//也可以這樣寫
class A
{
public:
static A& getInstance(return a;);
setup(){}
private:
A();
A(const A& ths);
};
A& A::getInstance()
{
static A a;
return a;
}
三、cout 補充(爲啥它能接受各式各樣類型的打印)
cout的源代碼
可以說 cout屬於一種 ostream,然後ostream裏有各種各樣的函數,於是cout 可以接受各種類型的打印
四、class template,類模板
template<typename T>//說明目前T還沒有綁定,不知道是什麼,於是下面的class成爲了 class template
class complex
{
public:
complex(T r = 0,T i = 0)
:re (r),im (i)
{}
complex& operator += (const complex&);
T real () const {return re;}
T imag () const {return im;}
private:
T re, im;
frienf complex& _doapl(complex* const complex&);
};
complex<double> c1(2.5 , 1.5);
complex<int> c2(2,6);
五、function template,函數模板
template<class T>
inline
const T& min(const T& a ,const T& b )
{
return a<b?b:a;
}
class stone
{
public:
stone(int w,int h,int we)
:_w(w),_h(h),_weight(we)
{}
bool operator < (const stone& rhs) const{return _weight<rhs._weight;}
private:
int _w,_h_weight;
};
stone r1(2,3),r2(3,3),r3;
r3=min(r1,r2);


六、namespace
namespace std  //指所有的東西被包裝在這個命名空間內
{


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章