C++静态成员变量和静态成员函数 - 人工智能之路
参考:C++程序设计 3.3.1 静态成员变量和静态成员函数
为什么要有这玩意
静态成员变量本质是全局变量,静态成员函数本质是全局函数。
将和某些类紧密相关的全局变量和函数写到类里面,看上去像一个整体,易于维护和理解。
#include <iostream>#include <stdio.h>//#include "Rectangle.hpp"using namespace std;// 应该放在Rectangle.hpp中// -------Rectangle.hpp----------class Rectangle {public: int width; int height; static int total; // 静态成员变量 Rectangle(int width, int height); Rectangle(Rectangle & r); ~Rectangle(); static void printTotal(); // 静态成员函数};// -------Rectangle.hpp----------// 应该放在Rectangle.cpp中// -------Rectangle.cpp----------Rectangle::Rectangle(int width, int height) { this->width = width; this->height = height; total++;}Rectangle::Rectangle(Rectangle & r) { *this = r; total++;}Rectangle::~Rectangle() { total--;}void Rectangle::printTotal() { // 现实时不能加static cout << total << endl;}int Rectangle::total = 0; // 静态成员变量初始化// int Rectangle::total; // 静态成员变量声明// -------Rectangle.cpp----------int main() { Rectangle r1(1, 1); Rectangle * pR2 = new Rectangle(2, 2); Rectangle r3 = r1; cout << "height = " << r3.height << endl; Rectangle::printTotal(); delete pR2; Rectangle::printTotal(); return 0;}
定义
在变量或函数前加static关键字
class Rectangle {public: static int total; // 静态成员变量 static void printTotal(); // 静态成员函数};
内存
静态成员变量只会创建一个,由所有对象共享
sizeof不会计算静态成员变量
访问
静态成员变量和函数的访问方式相同
推荐第一种,一看就知道是在访问静态的...
// 1. 类Rectangle::printTotal(); // 2. 对象Rectangle r;r.printTotal();// 3. 指针Rectangle * p = &r;p->printTotal();// 4. 引用Rectangle & ref = r;ref.printTotal();
调用
静态成员函数不依赖于类,因此它不能调用非静态成员函数和变量。
非静态成员函数,则可以随意调用静态成员变量和函数。