在函数声明和定义可能与参数的常量不一致时偶然发现。我发现了一些信息(下面的链接),但我的问题是为什么常量匹配是按值参数可选的,但是常量匹配是否需要参考参数?函数参数:常量匹配声明和定义
请考虑以下代码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