在函數聲明和定義可能與參數的常量不一致時偶然發現。我發現了一些信息(下面的鏈接),但我的問題是爲什麼常量匹配是按值參數可選的,但是常量匹配是否需要參考參數?函數參數:常量匹配聲明和定義
請考慮以下代碼here。
class MyClass
{
int X;
int Y;
int Z;
public:
void DoSomething(int z, int y, const int& x);
int SomethingElse(const int x);
void Another(int& x);
void YetAnother(const int& z);
};
void MyClass::DoSomething(int z, const int y, const int& x) // const added on 2nd param
{
Z = z;
Y = y;
X = x;
}
int MyClass::SomethingElse(int x) // const removed from param
{
X = x;
x = 3;
return x;
}
void MyClass::Another(int& x) // const not allowed on param
{
X = x;
}
void MyClass::YetAnother(const int& z) // const required on param
{
Z = z;
}
我找到了this on SO,但它正在尋找對名稱的修改的解釋。我還發現了this on SO和this on SO,但他們沒有詳細說明爲什麼const參數需要參考參數。
不匹配被討論[這裏](http://stackoverflow.com/q/20659000/1460794)。 – wally
這不是一個重複的問題。我沒有發現一個關於常量的問題,關於價值和借鑑,以及爲什麼**有一個區別。儘管[this](http://stackoverflow.com/questions/117293/use-of-const-for-function-parameters)有一個確實包含了引用的答案,但它不是很明顯,因爲問題在於by-價值,它不回答**爲什麼**有差異。 – bamakid