2014-01-17 99 views
2

我有一類叫做櫃檯和我的賦值運算符是這樣的:const引用混亂

const counter& counter::operator=(const counter& y) 
{ 
    count = y.count; 
    return *this; 
} 

現在,我的困惑從返回值莖:

const counter& counter:: ... 

我覺得這意味着計數器的賦值運算符應該返回一個常量計數器引用,並且由於它是const對象應該是不可變的,但據我所知它不是。

這裏是我的counterTest代碼,我已經在我的顧慮說:

#include "counter.h" 
#include <iostream> 

using std::cout; 
using std::endl; 

int main() 
{ 
    counter c; // c.count = 0 

    c.Inc(); // c.count = 1 
    c.Inc(); // c.count = 2 

    counter c2; 

    // Here I use my assignment operator so shouldn't c2 be immutable? 
    c2 = c; // c3.count = 2 

    // Why does this work? 
    c2.Inc(); // c3.count = 3 
    c2.Inc(); // c3.count = 4 

    cout << "c = " << c.Count() << ", c2 = " << c2.Count() 
      << endl; // prints: c = 2, c2 = 4 
} 

回答

6

這是你如何聲明c2

counter c2; 

正如你所看到的,它不是const。這永遠不會改變。您的任務不可能更改c2const

在您的分配功能中,它是*this,它指向您要分配的對象,而不是返回值。返回值是表達式c2 = c的值。因此,如果您嘗試修改結果,可能是(c2 = c).Inc(),它將無法正常工作,因爲返回值爲const


我注意到你似乎認爲const counter& counter::是函數的返回類型。其實,只是const counter&是。 counter::部分是嵌套名稱說明符,表示operator=函數是counter類的成員。

const counter& counter::operator=(const counter& y) 
^^^^^^^^^^^^^^ ^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^^^^^^ 
return type scope func name parameters 
+1

不是一個限定符(這將是像'const'這樣的關鍵字),而是範圍。 –

+0

@JoachimPileborg那麼他們被稱爲合格的ID。但是,範圍是一個更友好的描述。 –

+0

即使'const counter&counter ::'或'const counter&counter'是什麼有效類型? – mb84

0

隨着

const counter& counter::operator=(const counter& y)

您只需更改標準operator=這將在您不能連接它在這個特殊形式的方式被定義爲counter& counter::operator=(const counter& y)的含義:(a=b)=c。或者也不是(a=b).Inc()。但一個正常的a=b=c將是可能的。

變量必須明確定義爲const之前您使用任何運算符。取決於返回類型,它不能得到const。因此,就像已經說過的那樣,你需要將c2定義爲const。

編輯:

,你也應該考慮寫一個自己的拷貝構造函數,因爲const c2 = c只會像operator=被調用,但事實上,拷貝構造函數被調用(在這種情況下會成爲僅僅是會員的淺層副本的默認會員)。