C++开发初级


844 浏览 5 years, 3 months

5.4 常量引用数据成员

版权声明: 转载请注明出处 http://www.codingsoho.com/

常量引用数据成员

就像一个普通引用可以引用常量对象一样,引用成员也可以引用常量对象。例如,您可能决定让Spreadsheet只包含应用程序对象的常量引用,为此只需要简单地在类定义中将mTheApp声明为常量引用:

class SpreadsheetApplication; // forward declaration

class Spreadsheet
{
 public:
  Spreadsheet(int inWidth, int inHeight,
          const SpreadsheetApplication& theApp);
 protected:
  const SpreadsheetApplication& mTheApp;
}; 

代码取自 SpreadsheetDataMembers\Spreadsheet.h

常量引用以及非常量引用之间存在一个重要差别。常量引用SpreadsheetApplication数据成员只能用于调用SpreadsheetApplication对象上的常量方法。如果试图通过常量引用调用非常量方法,编译器会报错。

还可以创建静态引用成员或者静态常量引用成员,但一般不需要这么做。