staticios
complex設計模式
data members函數
static data membersthis
member functionsspa
static member functions設計
非靜態成員函數:non-static member functions對象
complex c1, c2, c3 complex c1, c2, c3內存
cout << c1.real(); ------------------> cout << complex::real(&c1); -----------------------> non-static data membersci
cout << c2.real(); ------------------> cout << complex::real(&c2); -----------------------> non-static data membersget
static data members 靜態數據 「僅有一份」
static member functions 靜態函數 --------------> 沒有thispointer,因此靜態函數只能處理靜態數據
進一步補充,static:
class Account{
public:
static double m_rate;
static void set_rate(const double& x) {m_rate = x;} 靜態函數沒有thispointer因此只能調用靜態數據
};
double Account::m_rate = 8.0; 靜態數據必須在class外面進行定義(定義獲取內存)
int main(){
Account::set_rate(5.0); 調用static函數的方式有兩種:
Account a; (1) 經過object調用,經過對象調用
a.set_rate(7.0); (2) 經過class name調用,經過類名調用
}
進一步補充,把ctors放在private中,把構造函數放在private中
class A{
public:
static A& getInstance(return a;) getInstance(return a;)外界能夠經過a來獲取對象
setup() {...}
private:
A(); 將A放在private裏面,那麼沒有任何人能夠建立A
A(const A& rhs);
static A a;
}
A::getInstance().setup(); 單例設計模式; 經過調用函數來實現,調用本身
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
上述表例中,若沒有本身則會形成浪費,例如static A a中, 若不須要建立則形成浪費。
class A{
public:
static A& getInstance();
setup() {...}
private:
A();
A(const A& rhs);
...
};
A& A::getInstance(){ A::getInstance().setup();
static A a;
return a;
}
進一步補充:class template, 類模板
template <typename T>
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;
friend 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 b < a ? b : a;
}
類模板與函數模板的差異
1.
類模板在使用時,必須指定類型是什麼?
函數模板沒必要明確指出,編譯器會進行參數推倒。
進一步補充:namespace
namespace std{ 能夠分爲不一樣模塊進行包裝
...
}
using directive
#include <iostream.h>
using namespace std; 所有打開
int main(){
cin << ...;
cout << ...;
return 0;
}