36.C++通过指针访问类的静态成员

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值