在以下 C++ 函数中:
void MyFunction(int age, House &purchased_house)
{
...
}
void MyFunction(const int age, House &purchased_house)
{
...
}
哪个更好?
在两者中,“年龄”都是按值传递的。我想知道 'const' 关键字是否是必要的:这对我来说似乎是多余的,但也很有帮助(作为变量不会改变的额外指示)。
有没有人认为以上哪一项(如果有的话)更好?
最佳答案
首先,它只是一个实现细节,if 你把 const 放在那里,不要把它放在声明集(标题)中。只放在实现文件中:
// header
void MyFunction(int age, House &purchased_house);
// .cpp file
void MyFunction(const int age, House &purchased_house);
{
...
}
定义中的参数是否为 const 纯粹是实现细节,不应成为接口(interface)的一部分。
我不经常看到这种事情,我也不会这样做。拥有参数 const 会比帮助更让我感到困惑,因为我会立即将其模式匹配失败为“const int &age” :) 当然,这与在另一个级别拥有 const 完全不同:
// const is a *good* thing here, and should not be removed,
// and it is part of the interface
void MyFunction(const string &name, House &purchased_house);
{
...
}
在这种情况下,const 会影响函数是否可以改变调用者的参数。应尽可能经常使用此含义的 const,因为它有助于确保程序的正确性并改进代码的自文档化。
关于C++ const 关键字 - 随意使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1554750/