zoukankan      html  css  js  c++  java
  • 指针指向类的静态数据成员

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

  • 相关阅读:
    LeetCode(122. 买卖股票的最佳时机 II)
    LeetCode(485. 最大连续1的个数)

    约瑟夫问题
    链表
    队列
    稀疏数组
    乐优商城项目学习
    LeetCode_Climbing Stairs
    数据结构&&算法基础知识
  • 原文地址:https://www.cnblogs.com/dongyanxia1000/p/4906607.html
Copyright © 2011-2022 走看看