在C++中,若类中的数据成员是静态数据成员,则必须在类外进行初始化和定义,并且需要用 :: 来指明其所属的类.
用static声明该数据成员
#include <iostream>
using namespace std;
class Point{
public:
Point(int x = 0,int y = 0) //构造函数
: x(x),y(y){
count++;
};
Point(Point &p){ //复制构造函数
x = p.x;
y = p.y;
count++;
}
~Point(){count--;}
int getX(){return x;}
int getY(){return y;}
void showCount(){
cout << " Object count = " << count << endl;
}
private:
int x,y;
static int count;
};
int Point::count = 0; //静态数据成员必须在类外定义和初始化
int main(){
Point a(4,5);
cout << "Point A: " << a.getX() << ", " << a.getY();
a.showCount();
Point b(a);
cout << "Point B: " << b.getX() << ", " << b.getY();
b.showCount();
return 0;
}
对于静态函数成员,其只能引用属于该类的静态数据成员或静态成员函数:
,且在使用该函数的时候,需用 类::函数名(); 的格式
#include <iostream>
using namespace std;
class Point{
public:
Point(int x = 0,int y = 0)
: x(x), y(y){
count++;
}
Point(Point &p){
x = p.x;
y = p.y;
count++;
}
~Point(){count--;}
int getX(){return x;}
int getY(){return y;}
static void showCount(){
cout << " Object count = " << count << endl;
} //此处写法
private:
int x,y;
static int count;
};
int Point::count = 0;
int main(){
Point a(4,5);
cout << "Point A: " << a.getX() << ", " << a.getY();
Point::showCount(); //注意此处写法
Point b(a);
cout << "Point B: " << b.getX() << ", " << b.getY();
Point::showCount(); //注意此处写法
return 0;
}