与C ++中的const关键字的区别

时间:2015-10-15 08:39:26

标签: c++ const

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

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

我希望通过示例有一个明确的解释,以帮助我理解这些差异。

2 个答案:

答案 0 :(得分:2)

以下是最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成员函数。

Const引用也可用于prolong the lifetime of temporaries

答案 1 :(得分:0)

 (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)。