89.类的静态函数

  • 静态函数没有this指针,无法调用成员变量与成员函数
  • 没有对象名也可以访问,也可以通过对象名访问
  • 静态成员函数经常与静态成员数据配合使用

代码示例

 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <vector>
 4 using namespace std;
 5 
 6 //类实现静态函数管理静态数据
 7 class myclass
 8 {
 9 public:
10     static vector<myclass *>all;
11     int x;
12     int y;
13 
14 public:
15     myclass(int a,int b)
16     {
17         x = a;
18         y = b;
19         all.push_back(this);//每次构造压入
20     }
21     void go()
22     {
23         cout << (void *)this << endl;//this是当前对象的首地址
24     }
25 
26     void show()
27     {
28         cout << "hello" << endl;
29     }
30 
31     static void show2(int data)
32     {
33         //静态函数无法使用this
34         //无法访问内部变量,不能访问类成员函数
35         cout << "hello2" << endl;
36     }
37 
38     static void showall();
39 };
40 
41 //前面是类型      后面的对象
42 vector<myclass *> myclass::all;
43 
44 //可以对C语言实现功能函数,分类包装到类,可以直接用类名调用
45 class tools
46 {
47 public:
48     static void runcmd(char *cmd)
49     {
50         system(cmd);
51     }
52 
53     //类静态函数和静态成员变量进行结合,操作静态数据
54     static int add(int a, int b)
55     {
56         return a + b;
57     }
58 };
59 
60 void myclass::showall()
61 {
62     for (auto i : all)
63     {
64         cout << (*i).x << (*i).y << endl;
65     }
66 }
67 
68 void main()
69 {
70     void(*p)(int) = &myclass::show2;//因为没有this指针,所以不需要指明对象
71     void(myclass::*px)() = &myclass::show;//因为有this指针,所以需要指明对象
72 
73     //访问静态函数,无需对象名就可以访问,也可以通过对象名访问
74     myclass::show2(2);
75     myclass my1(1,2);
76     my1.show2(3);
77 
78     tools::runcmd("calc");
79     tools ts;
80     ts.runcmd("notepad");
81     cin.get();
82 }
原文地址:https://www.cnblogs.com/xiaochi/p/8593764.html