程序實例:
class CRectangle
{
private:
int w, h;
static int nTotalArea; //靜態成員變量
static int nTotalNumber;
public:
CRectangle(int w_,int h_);
~CRectangle();
static void PrintTotal(); //靜態成員函數
};訪問靜態成員:
注意Tips:
在靜態成員函數中,不能訪問非靜態成員變量,也不能調用非靜態成員函數。
例如:
void CRectangle::PrintTotal()
{
cout << w << "," << nTotalNumber << "," << nTotalArea << endl; //wrong
}
CRetangle::PrintTotal(); //解釋不通,w 到底是屬於那個對象的?
CRectangle::CRectangle(int w_,int h_)
{
w = w_;
h = h_;
nTotalNumber ++;
nTotalArea += w * h;
}
CRectangle::~CRectangle()
{
nTotalNumber --;
nTotalArea -= w * h;
}
void CRectangle::PrintTotal()
{
cout << nTotalNumber << "," << nTotalArea << endl;
}