我有一類叫做櫃檯和我的賦值運算符是這樣的: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
}
不是一個限定符(這將是像'const'這樣的關鍵字),而是範圍。 –
@JoachimPileborg那麼他們被稱爲合格的ID。但是,範圍是一個更友好的描述。 –
即使'const counter&counter ::'或'const counter&counter'是什麼有效類型? – mb84