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

关于c++中的静态成员变量

时间:2016-06-26 19:46:39      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

下面通过1个例子来解释一下:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std ;
 4 
 5 
 6 class student
 7 {
 8     private://把变量声明为私有的
 9     int num ;
10     string name ;
11     int math ;
12     int english ;
13     int total ;
14     static string teacher;
15     void cacu_total();
16     
17     public:
18     void input_stu();
19     void output_stu();
20 };
21 
22 string student::teacher = "xiaoming";
23 int main(int argc , char *argv[])
24 {
25     student stu1,stu2;
26     student *pstu;
27     pstu = new student ;
28     stu1.input_stu();
29     stu2.input_stu();
30     pstu->input_stu();
31     
32     stu1.output_stu();
33     stu2.output_stu();
34     pstu->output_stu();
35     delete pstu ;
36     return 0;
37 }

对于上述代码的解释:定义了2个类的变量stu1 stu2 怎么对于他们的成员变量 

比如说 stu1 的num name math等变量和stu2 的num name math等变量 是不同的变量

而对于teacher这个成员变量, stu1 和stu2 是一样的,即在stu1中改变teacher的值 stu2中teacher的值也会改变

因为他们占用的是同一块内存。

 

可以这样理解 静态成员变量相当于是在类中定义一个全局变量,他不保存在每个对象的数据中,整个类只有1份

 

还有一点需要特别注意,静态成员变量除了在类中声明外,还必须在外部明确定义

就是上面的这一句:

string student::teacher = "xiaoming";

 

关于c++中的静态成员变量

标签:

原文地址:http://www.cnblogs.com/tiantiantian-dianzi/p/5618419.html

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