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 void showcount() 19 { 20 cout << "object count = "<< count <<endl; 21 } 22 private: 23 int x,y; 24 static int count; 25 }; 26 int Point::count = 0; //静态数据成员定义和初始化,使用类名限定 27 int main() 28 { 29 void (* funcptr)() = Point::showcount; //定义一个函数指针,指向类的静态成员函数 30 Point a(4,5); 31 cout << "Point A:" << a.getx() << "," << a.gety() << endl; 32 funcptr(); 33 Point b(a); //用对象a来初始化b,调用复制构造函数 34 cout << "Point B:" << b.getx() << "," << b.gety() << endl; 35 funcptr(); 36 system("pause"); 37 return 0; 38 }

    2. 运行结果:

    调用一次构造函数Point(x, y),count++

    调用一次复制构造函数(拷贝构造函数)Point(&p),count++.

    Note: count成员变量是static类型的,只初始化一次,并保存后面改变后的值。

    3、static全局变量与普通全局变量的共同点和区别

    共同点:生命周期,都是从开始定义一直到程序运行结束

    不同点:作用域,static全局变量限定了它的作用域,只能用于本文件中。

    4、static局部变量和普通局部变量的共同点和区别

    共同点:作用域,作用在定义它的函数中

    不同点:生命周期,static的局部变量从定义开始就一直存在到程序结束,而普通的局部变量在函数调用完成后就不存在。

    即从存储空间的角度来说,static的局部变量一直占有内存,而普通的局部变量函数调用完成后会释放内存。

  • 相关阅读:
    BZOJ 3033 太鼓达人(DFS+欧拉回路)
    HDU 5121 Just A Mistake
    HDU 5120 Intersection
    HDU 5119 Happy Matt Friends
    HDU 5117 Fluorescent
    BZOJ 1088: [SCOI2005]扫雷Mine
    Codeforces 994 C
    BZOJ 2242: [SDOI2011]计算器
    HDU 4609 3-idiots
    算法笔记--FFT && NTT
  • 原文地址:https://www.cnblogs.com/dongyanxia1000/p/4906592.html
Copyright © 2011-2022 走看看