008_linuxC++之_类的静态变量和静态函数

(一)看程序

008_linuxC++之_类的静态变量和静态函数

 1 #include <iostream>
 2 #include <string.h>
 3 #include <unistd.h>
 4 
 5 using namespace std;    
 6 
 7 class Person {
 8 private:
 9     static int cnt;        /*静态变量,在33行中初始化为0*/
10     char *name;        
11 
12 public:
13 
14     static int getCount(void);     /*静态函数*/
15 
16     Person() {    /*当运行一次结构体定义时候就会运行一次这个,具体看007构造函数*/
17         name = NULL;
18         cnt++;
19     }
20     ~Person()        /*释放时候自动运行,看007构造函数*/
21     {
22         cout << "~Person()"<<endl;
23     }
24 
25 };
26 
27 int Person::cnt = 0; /* 定义和初始化 */
28 
29 int Person::getCount(void) 
30 { 
31     return cnt; 
32 }
33 
34 
35 int main(int argc, char **argv)
36 {
37     Person p[100];
38     cout << "person number = "<<Person::getCount()<<endl;    /*静态变量输出100*/
39     cout << "person number = "<<p[0].getCount()<<endl;        /*静态变量输出100*/
40     cout << "person number = "<<p[1].getCount()<<endl;        /*静态变量输出100*/
41 
42     return 0;
43 }

main.cpp

运行结果

008_linuxC++之_类的静态变量和静态函数

 

(二)静态函数中不能调用非静态的变量

如,name的初始化在静态函数中使用会编译出错

008_linuxC++之_类的静态变量和静态函数

编译结果

008_linuxC++之_类的静态变量和静态函数

 008_linuxC++之_类的静态变量和静态函数

原文链接: https://www.cnblogs.com/luxiaoguogege/p/9690566.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    008_linuxC++之_类的静态变量和静态函数

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/281661

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午5:51
下一篇 2023年2月15日 上午5:53

相关推荐