下面经过几个例子来总结静态成员变量和静态成员函数的使用规则。ios
1、经过类名调用静态成员函数和非静态成员函数函数
1 //例子一:经过类名调用静态成员函数和非静态成员函数 2 class Point{ 3 public: 4 void init() 5 {} 6 7 static void output() 8 {} 9 }; 10 11 void main() 12 { 13 Point::init(); 14 Point::output(); 15 }
编译出错:错误 1 error C2352: “Point::init”: 非静态成员函数的非法调用this
结论一:不能经过类名来调用类的非静态成员函数spa
2、经过类的对象调用静态成员函数和非静态成员函数.net
1 //例子二:经过类的对象调用静态成员函数和非静态成员函数 2 class Point{ 3 public: 4 void init() 5 { 6 } 7 8 static void output() 9 {} 10 }; 11 12 void main() 13 { 14 Point pt; 15 pt.init(); 16 pt.output(); 17 }
编译经过。指针
结论二:类的对象可使用静态成员函数和非静态成员函数。对象
3、在类的静态成员函数中使用类的非静态成员blog
1 //例子三:在类的静态成员函数中使用类的非静态成员 2 #include <iostream> 3 using namespace std; 4 5 class Point{ 6 public: 7 void init() 8 { 9 } 10 static void output() 11 { 12 cout << "m_x=" << m_x << endl; 13 } 14 private: 15 int m_x; 16 }; 17 void main() 18 { 19 Point pt; 20 pt.output(); 21 }
编译出错:IntelliSense: 非静态成员引用必须与特定对象相对内存
由于静态成员函数属于整个类,在类实例化对象以前就已经分配空间了,而类的非静态成员必须在类实例化对象后才有内存空间,因此这个调用就会出错,就比如没有声明一个变量却提早使用它同样。get
结论三:静态成员函数中不能引用非静态成员。
4、在类的非静态成员函数中使用类的静态成员
1 //例子四:在类的非静态成员函数中使用类的静态成员 2 #include <iostream> 3 using namespace std; 4 5 class Point{ 6 public: 7 void init() 8 { 9 output(); 10 } 11 static void output() 12 { 13 } 14 private: 15 int m_x; 16 }; 17 void main() 18 { 19 Point pt; 20 pt.init(); 21 }
编译经过。
结论四:类的非静态成员能够调用静态成员函数,但反之不能。
5、使用类的静态成员变量
1 //例子五:使用类的静态成员变量 2 #include <iostream> 3 using namespace std; 4 5 class Point{ 6 public: 7 Point() 8 { 9 m_nPointCount++; 10 } 11 ~Point() 12 { 13 m_nPointCount++; 14 } 15 static void output() 16 { 17 cout << "m_nPointCount=" << m_nPointCount << endl; 18 } 19 private: 20 static int m_nPointCount; 21 }; 22 23 void main() 24 { 25 Point pt; 26 pt.output(); 27 }
连接出错:error LNK2001: 没法解析的外部符号 "private: static int Point::m_nPointCount" (?m_nPointCount@Point@@0HA)
这是由于类的成员变量在使用前必须先初始化。
改为以下代码便可:
1 #include <iostream> 2 using namespace std; 3 4 class Point{ 5 public: 6 Point() 7 { 8 m_nPointCount++; 9 } 10 ~Point() 11 { 12 m_nPointCount++; 13 } 14 static void output() 15 { 16 cout << "m_nPointCount=" << m_nPointCount << endl; 17 } 18 private: 19 static int m_nPointCount; 20 }; 21 22 //类外初始化静态成员变量时,不用带static关键字 23 int Point::m_nPointCount = 0; 24 void main() 25 { 26 Point pt; 27 pt.output(); 28 }
运行结果:
结论五:类的静态成员变量必须先初始化再使用。