码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-10-24 12:50:43      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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的。

 

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

标签:

原文地址:http://www.cnblogs.com/dongyanxia1000/p/4906607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!