【发布时间】:2016-08-15 06:31:08
【问题描述】:
偶然发现这个函数声明和定义可能在参数的常量上不一致。我找到了一些信息(链接如下),但我的问题是为什么 const 匹配对于按值参数是可选的,而对于引用参数则需要 const 匹配?
考虑以下可用的代码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 匹配。
【问题讨论】:
标签: c++