指针指向类的静态数据成员

1. 代码

 1 #include<iostream>
 2 #include<stdio.h>
 3 using namespace std;
 4 class Point
 5 {
 6     public:
 7     Point(int x=0,int y=0):x(x),y(y)
 8     { 
 9        count++;
10     }
11     Point(const Point &p):x(p.x),y(p.y)
12     { 
13        count++;
14     }
15     ~Point(){ count--;}
16     int getx() const {return x;}
17     int gety() const {return y;}
18     static int count;//注意要定义到public的下面,才有访问权限
19     private:
20     int x,y;    
21 };
22 int Point::count=0;  //静态数据成员定义和初始化,使用类名限定
23 int main()
24 { 
25     int *ptr=&Point::count;  //定义一个int型指针,指向类的静态成员
26     Point a(4,5);
27     cout<<"Point A:"<<a.getx()<<","<<a.gety()<<endl;
28     cout<<"object count="<<*ptr<<endl;
29     Point b(a);    //用类的一个对象做另一个对象的参数,调用复制构造函数
30     cout<<"Point B:"<<b.getx()<<","<<b.gety()<<endl;
31     cout<<"object count="<<*ptr<<endl;
32     system("pause");
33     return 0;
34 }

2. 运行结果如下图:

Note:count类型是static,且访问权限是public的。

 

转载于:https://www.cnblogs.com/dongyanxia1000/p/4906607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值