我应该返回const对象吗?

在Effective C++项目03中,尽可能使用const。


class Bigint

{

  int _data[MAXLEN];

  //...

public:

  int& operator[](const int index) { return _data[index]; }

  const int operator[](const int index) const { return _data[index]; }

  //...

};

const int operator[]确实与有所不同int& operator[]。


但是关于:


int foo() { }


const int foo() { }

好像他们是一样的。


我的问题是,为什么我们使用const int operator[](const int index) const代替int operator[](const int index) const?


德玛西亚99
浏览 398回答 3
3回答

qq_遁去的一_1

非类类型的返回类型的顶级cv限定词将被忽略。这意味着即使您编写:int const foo();返回类型为int。如果返回类型是引用,则当然const不再是顶级,并且它们之间的区别是:int& operator[]( int index );和int const& operator[]( int index ) const;是重要的。(也请注意,在函数声明中,如上述一样,所有顶级cv限定词也将被忽略。)区别也与类类型的返回值有关:如果返回T const,则调用者无法在返回的值上调用非const函数,例如:class Test{public:    void f();    void g() const;};Test ff();Test const gg();ff().f();             //  legalff().g();             //  legalgg().f();             //  **illegal**gg().g();             //  legal
打开App,查看更多内容
随时随地看视频慕课网APP