码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-22 18:18:22      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:names   技术   运行   spl   出错   分享图片   inux   stream   hid   

(一)看程序

技术分享图片
 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

运行结果

技术分享图片

 

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

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

技术分享图片

编译结果

技术分享图片

 

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

标签:names   技术   运行   spl   出错   分享图片   inux   stream   hid   

原文地址:https://www.cnblogs.com/luxiaoguogege/p/9690566.html

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