// 静态成员变量类内初始化,编译报错,因为静态成员属于整个类,而不属于某个对象,如果在类内初始化,会导致每个对象都包含该静态成员,这是矛盾的 classTest { public: staticchar c = 'A'; // error: ISO C++ forbids in-class initialization of non-const static member ‘Test::c’ };
classTest { public: staticvoidshow() { cout << n << endl; } private: staticint n; }; int Test::n = 1; intmain() { Test::show(); // 1,通过类名作用域调用 Test t; t.show(); // 1,通过对象调用 }
与静态成员变量不同的是,静态成员函数的作用是为了能处理静态成员变量。当调用一个对象的成员函数(非静态成员函数)时,系统会把该对象的起始地址赋给成员函数的 this 指针;而静态成员函数并不属于某一对象,因此静态成员函数没有 this 指针,既然它没有指向某一对象,就无法对一个对象中的非静态成员进行默认访问(即在引用数据成员时不指定对象名)
// 静态成员函数访问非静态成员变量和非静态成员函数,编译报错 classTest { public: staticvoidshow() { add(7); // error: cannot call member function ‘void Test::add(int)’ without object cout << i << endl; // error: invalid use of member ‘Test::i’ in static member function } voidadd(int j) { i += j; } private: int i; };
// 但是,静态成员函数并不是绝对不能引用本类中的非静态成员,只是不能进行默认访问,因为无法知道应该去找哪个对象 classTest { public: staticvoidshow(Test a) { a.add(7); cout << a.i << endl; } voidadd(int j) { i += j; } private: int i; };
// 非静态成员函数可以访问静态成员函数和静态成员变量 classTest { public: voidshow() { add(i); cout << n << ' ' << i << endl; } staticvoidadd(int j) { n += j; } private: int i{7}; staticint n; }; int Test::n = 1; intmain() { Test t; t.show(); // 8 7 }