代码部分转载自:C++ 类的静态成员及静态成员函数
一、通过类名调用静态成员函数和非静态成员函数
//例子一:通过类名调用静态成员函数和非静态成员函数 class Point{ public: void init() {} static void output() {} }; void main() { Point::init(); Point::output(); }
编译出错:错误 1 error C2352: “Point::init”: 非静态成员函数的非法调用
结论一:不能通过类名来调用类的非静态成员函数
二、通过类的对象调用静态成员函数和非静态成员函数
//例子二:通过类的对象调用静态成员函数和非静态成员函数 class Point{ public: void init() { } static void output() {} }; void main() { Point pt; pt.init(); pt.output(); }
编译通过。
结论二:类的对象可以使用静态成员函数和非静态成员函数。
三、在类的静态成员函数中使用类的非静态成员
//例子三:在类的静态成员函数中使用类的非静态成员 #include <iostream> using namespace std; class Point{ public: void init() { } static void output() { cout << "m_x=" << m_x << endl; } private: int m_x; }; void main() { Point pt; pt.output(); }
编译出错:IntelliSense: 非静态成员引用必须与特定对象相对
因为静态成员函数属于整个类,在类实例化对象之前就已经分配空间了,而类的非静态成员必须在类实例化对象后才有内存空间,所以这个调用就会出错,就好比没有声明一个变量却提前使用它一样。
结论三:静态成员函数中不能引用非静态成员。
四、在类的非静态成员函数中使用类的静态成员
//例子四:在类的非静态成员函数中使用类的静态成员 #include <iostream> using namespace std; class Point{ public: void init() { output(); } static void output() { } private: int m_x; }; void main() { Point pt; pt.init(); }
编译通过。
结论四:类的非静态成员可以调用静态成员函数,但反之不能。
五、使用类的静态成员变量
//例子五:使用类的静态成员变量 #include <iostream> using namespace std; class Point{ public: Point() { m_nPointCount++; } ~Point() { m_nPointCount++; } static void output() { cout << "m_nPointCount=" << m_nPointCount << endl; } private: static int m_nPointCount; }; void main() { Point pt; pt.output(); }
链接出错:error LNK2001: 无法解析的外部符号 "private: static int Point::m_nPointCount" (?m_nPointCount@Point@@0HA)
这是因为类的成员变量在使用前必须先初始化。
改成如下代码即可:
#include <iostream> using namespace std; class Point{ public: Point() { m_nPointCount++; } ~Point() { m_nPointCount++; } static void output() { cout << "m_nPointCount=" << m_nPointCount << endl; } private: static int m_nPointCount; }; //类外初始化静态成员变量时,不用带static关键字 int Point::m_nPointCount = 0; void main() { Point pt; pt.output(); }
结论五:类的静态成员变量必须先初始化再使用。
原文:https://www.cnblogs.com/zhizhiyu/p/10153103.html