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


    下面通过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";
  • 相关阅读:
    codeforces 814B An express train to reveries
    codeforces 814A An abandoned sentiment from past
    codeforces 785D D. Anton and School
    codeforces 785C Anton and Fairy Tale
    codeforces 791C Bear and Different Names
    AOP详解
    Spring集成JUnit测试
    Spring整合web开发
    IOC装配Bean(注解方式)
    IOC装配Bean(XML方式)
  • 原文地址:https://www.cnblogs.com/tiantiantian-dianzi/p/5618419.html
Copyright © 2020-2023  润新知