【问题标题】:Differences with const keyword in C++与 C++ 中 const 关键字的区别
【发布时间】:2015-10-15 08:39:25
【问题描述】:

在 C++ 中,我很难理解这 3 种使用 const 的方式之间的区别:

int get() const {return x;}        
const int& get() {return x;}      
const int& get() const {return x;} 

我想通过示例进行清晰的解释,以帮助我理解差异。

【问题讨论】:

  • 每一本c++基础教科书都已经很好的解释了。

标签: c++ constants


【解决方案1】:

这是最const的例子:

class Foo
{
    const int * const get() const {return 0;}
    \_______/   \___/       \___/
        |         |           ^-this means that the function can be called on a const object
        |         ^-this means that the pointer that is returned is const itself
        ^-this means that the pointer returned points to a const int    
};

在你的特殊情况下

//returns some integer by copy; can be called on a const object:
int get() const {return x;}        
//returns a const reference to some integer, can be called on non-cost objects:
const int& get() {return x;}      
//returns a const reference to some integer, can be called on a const object:
const int& get() const {return x;} 

This question 详细解释了const 成员函数。

常量引用也可以用于prolong the lifetime of temporaries

【讨论】:

  • 不错的答案,但我会稍微扩展一下 const 成员函数的部分。可以在 const 对象上调用它,是的,但我要补充的是,它承诺不更改任何成员变量,也不调用任何非 const 成员函数,并且此承诺由编译器强制执行,如果你违反它会报错。
  • 谢谢@SingerOfTheFall,我知道这是一个基本问题,但我并不太清楚
【解决方案2】:
 (1) int get() const {return x;}   

我们这里有两个优势,

  1. const and non-const class object can call this function. 

  const A obj1;
  A obj1;

  obj1.get();
  obj2.get();

    2. this function will not modify the member variables for the class

    class A
    {
       public: 
         int a;
       A()
       {
           a=0;
       }
       int get() const
       {
            a=20;         // error: increment of data-member 'A::a' in read-only structure
            return x;
       }
     }

通过常量函数更改类[a]的成员变量时,编译器抛出错误。

    (2) const int& get() {return x;}  

返回指向常量整数引用的指针。

    (3)const int& get() const {return x;} 

是组合答案(2)和(3)。

【讨论】:

    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多