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

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