《C++高级程序程序设计》读书笔记(四)

          类的数据成员

          数据成员可以分为简单数据成员、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。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值