2016-08-30 68 views
0

我很新的C++來OOP和我碰到下面的代碼來同時在網上衝浪:C++ const函數錯誤

#include<iostream> 
using namespace std; 

class cls 
{int x; 
public: 
    cls(int i=3) {x=i;} 

    int &f() const{ return x;} 
}; 
int main() 
{ 
    const cls a(-3); 
    int b=a.f(); 
    cout<<b; 
    return 0; 
} 

,當我嘗試運行代碼,它崩潰因f函數。現在我不太確定那裏發生了什麼,爲什麼它會崩潰,所以我需要有人就這個問題點點啓發。

+6

^^^^^廢話! –

+3

@BatCoder所以,它會返回一個對所述變量的引用。 –

+2

[是否返回C++引用變量的做法,邪惡?](http://stackoverflow.com/questions/752658/is-the-practice-of-returning-ac-reference-variable-vil) –

回答

5

由於您的函數聲明爲const您不能將非const引用返回給成員變量,除非將其標記爲mutable

要解決你的代碼寫或者

class cls 
{ 
    mutable int x; 
// ^^^^^^^ 
public: 
    cls(int i=3) {x=i;} 

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

或返回const參考。

class cls 
{ 
    int x; 
public: 
    cls(int i=3) {x=i;} 

    const int &f() const{ return x;} 
// ^^^^^ 
}; 

使用mutable需要用一粒鹽採取,它會破壞你的類的封裝,並讓你的類內部通過你遞出的參考來改變。

+3

int f()const {return x;} ok –

+1

@KenmanTsang Yup。 –

+2

@KenmanTsang在_this_的情況下是可以的,事實上,這可能是明智的(複製一個'int'很容易)。但是,返回副本並不總是一個好主意,甚至是可能的。 –

1

您不能將一個非const引用返回給constconst成員函數訪問它時使變量xconst

似乎沒有必要返回一個參考,實際上這是一個不好的做法。如果你需要改變你的內部int它更有意義添加一個setter:

class cls 
{ 
    int x; 
public: 
    cls(int i=3) { set(i); } 
    void set (const int val) { x=val; } 
    int f() const{ return x; } 
};