定义 静态成员就是在成员变量和成员函数前加关键词static。
分类 静态成员变量
所以对象共享同一份数据
在编译阶段分配内存
类内声明,类外初始化
静态成员函数
所有对象共享同一函数
静态成员函数只能访问静态成员变量
简单实例 #include <iostream> #include <string> using namespace std;class Person { public : Person (); ~Person (); static int m_A; static void func () { m_A = 2000 ; cout << "static void 调用" << endl; } private :};
int Person::m_A = 10 ;Person::Person () { } Person::~Person () { } void test01 () { Person P; cout << "年龄:" << P.m_A << endl; Person p2; p2. m_A = 20 ; cout << "年龄:" << P.m_A << endl; } void test02 () { cout << "年龄:" << Person::m_A << endl; }
void test03 () { Person::func (); cout << "年龄:" << Person::m_A << endl; } void test04 () { Person P; P.func (); cout << "年龄:" << P.m_A << endl; }
static void 调用 年龄:2000 static void 调用 年龄:2000
int main () { test01 (); test02 (); test03 (); test04 (); system ("pause" ); return 0 ; }
书本实例 #include <iostream> #include <string> using namespace std;class Croster { string name; int Math; static int Sum; public : Croster (string na = "undef" , int m = 100 ); static int Count; static void Display () ; };
#include "l4_03.h" int Croster::Count = 100 ;int Croster::Sum;Croster::Croster (string na, int m) :name (na), Math (m) { cout << "欢迎新同学" << endl; Count--; Sum += Math; } void Croster::Display () { cout << "Sum:" << Sum << endl; if (Count == 100 ) { cout << "Average=0" << endl; } else cout << "Average=" << Sum * 1.0 / (100 - Count) << endl; }
#include "l4_03.h" int main () { Croster::Display (); Croster list[3 ] = { Croster ("赵衍" ,95 ),Croster ("钱多多" ,90 ),Croster ("孙立" ,92 ) }; list[1 ].Display (); Croster stu_A ("李梅" ) ; stu_A.Display (); return 0 ; }
Sum:0 Average=0 欢迎新同学 欢迎新同学 欢迎新同学 Sum:277 Average=92.3333 欢迎新同学 Sum:377 Average=94.25