`const`关键字是用于函数声明、定义还是两者兼而有之?
void test(int& in);
void test(const int& in){
}
int main(){
int a = 5;
test(a);
return 0;
}
上面没有编译链接错误:undefined reference to `test(int&)'。
我对此有3个问题:
1- 为什么我们会收到链接错误?是因为添加const到定义中使其成为完全不同的功能吗?为什么在不使用引用时它会起作用,即这可以正常工作:
void test(int in);
void test(const int in){}
..
int a = 5;
test(a);
..
2- 是否const进入函数声明、定义或两者?如果使用引用,行为似乎有所不同。
3-const参数上的关键字是否说“传递给我的参数应该是调用者中的常量”或“此参数在此函数范围内被视为常量,无论它在调用者中是否为常量”。我确定是后者,但想确认一下。
回答
在 C++ 中,两个函数:
void test(int& in);
void test(const int& in);
是两个不同的重载函数。第一个绑定到“可写”整数,第二个绑定到常量。
在您的代码中:
int a = 5;
test(a);
a是一个可修改的对象,因此void test (int &)从编译器的角度来看是一个更好的匹配,它选择这个函数进行调用。
您收到链接器错误的原因是您声明但未定义此函数。
在以下两种情况下,const都会选择该功能:
int const a = 5;
test(a);
test(10);
此外,如果您只有const如下声明的版本,它也会被选中:
//void test(int &in);
void test(const int &in){}
..
int a = 5;
test(a);
..
至于在引用的情况下的第二个问题 -const声明和定义都是不同的,因为它们是不同的功能。
对于正常值,声明时两者之间没有区别:
void test(int in);
void test(const int in);
它们指的是相同的功能。该const版本将防止修改函数定义中的函数参数。
对于第三个,当应用于引用时,它意味着两件事:
- 引用将传递给函数,而不是对象的副本。
- 当伴随着 a 时,
const它向调用者承诺不修改引用的对象并阻止函数这样做。