类的数据成员
数据成员可以分为简单数据成员、static数据成员、const成员、引用成员、const引用成员和其他成员。
静态数据成员是属于类而不是对象的数据成员,您可以将静态数据成员当做类的全局变量。
static数据成员在C++11以后只需要在类中声明并初始化,默认情况下它们会被初始化为0,static指针会被初始化为nullptr。
static int scounter=0;
而C++11以前在类中声明了静态数据变量后需要在类外为其分配空间并初始化。
int spreadsheet::scounter=0;
静态数据成员在类中的访问和普通成员一样,类外访问则需要在静态数据成员前加类和作用域运算符。
如果两个类之间互相有对方的对象,无法用#include加以解决,解决方案是在其中一个头文件中使用前置声明。
#include "SpreadsheetCell.h" class SpreadsheetApplication; // forward declaration class Spreadsheet { public: Spreadsheet(int inWidth, int inHeight, const SpreadsheetApplication& theApp); Spreadsheet(const Spreadsheet& src); ~Spreadsheet(); Spreadsheet& operator=(const Spreadsheet& rhs); void setCellAt(int x, int y, const SpreadsheetCell& cell); SpreadsheetCell getCellAt(int x, int y); int getId() const; // Doesn't work in Microsoft Visual Studio 6 static const int kMaxHeight = 100; static const int kMaxWidth = 100; protected: bool inRange(int val, int upper); void copyFrom(const Spreadsheet& src); int mWidth, mHeight; int mId; SpreadsheetCell** mCells;
const SpreadsheetApplication& mTheApp;
static int sCounter = 0; //static int sCounter; // Pre C++11}; 常量数据引用成员只能用于调用数据成员对象上的常量方法。const SpreadsheetApplication& mTheApp;
方法有时会应用于全部对象而不是单个对象,此时可以像使用静态成员那样使用静态方法。
在方法前加关键字static ,静态方法不能声明为const。