为了账号安全,请及时绑定邮箱和手机立即绑定

我应该返回const对象吗?

我应该返回const对象吗?

C++
德玛西亚99 2019-10-16 13:50:21
在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?
查看完整描述

3 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

非类类型的返回类型的顶级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();             //  legal

ff().g();             //  legal

gg().f();             //  **illegal**

gg().g();             //  legal


查看完整回答
反对 回复 2019-10-16
  • 3 回答
  • 0 关注
  • 398 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信