#include <iostream>
using namespace std;
//通过指针访问类的静态数据成员
class Point {
public://外部接口
Point(int x = 0, int y = 0) : x(x), y(y) {//构造函数
count++;
}
Point(const Point& p) :x(p.x), y(p.y) {//复制构造函数
count++;
}
int getX() const { return x; }//const 表示该函数不修改任何值;
int getY() const { return y; }
static int count;//静态数据成员声明,用于记录点的个数
private:
int x, y;
};
int Point::count = 0; //静态数据成员定义和初始化,使用类名限定
int main() {//主函数
int* ptr = &Point::count;//定义一个int型指针,指向类的静态成员
Point a(4, 5);
cout << "PointA:" << a.getX() << "," << a.getY();
cout << " Object count=" << *ptr << endl;
Point b(a);
cout << "PointB:" << b.getX() << "," << b.getY();
cout << " Object count:" << *ptr << endl;
return 0;
}
36.C++通过指针访问类的静态成员
最新推荐文章于 2024-01-28 13:02:50 发布