对象间共享变量和操作共享变量的成员函数前面加static

一、对象间共享变量
关注地方有如下:
1、怎么定义,怎么初始化
2、内存什么时候分配,分配在哪
3、作用是什么

二、静态成员函数只能访问静态成员变量和静态成员函数;

点击查看代码
/* Online C++ Compiler and Editor */
#include <iostream>

using namespace std;


class Student{
public:
    Student(char *name, int age, float score);
    void show();
    
public:
    static int m_total;  //静态成员变量


//private:
//    static int m_total;  //静态成员变量


private:
    char *m_name;
    int m_age;
    float m_score;
};

void Student::show()
{
    
    cout << m_total << endl; 
    
}

Student::Student(char *name, int age, float score)
{
    
    
}

int Student::m_total  = 1;

int main()
{
   //Student obj("a", 1, 1.3f);
   
   //obj.show();
   
   cout << Student::m_total << endl; 
   
   cout << sizeof(Student) << endl;
   cout << "Hello World" << endl; 
   
   return 0;
   
}

posted @ 2022-11-17 09:42  我爱茜茜公主  阅读(20)  评论(0)    收藏  举报