为什么相同的函数签名只有区别,另一个通过 const 获取参数是重新定义?

Why same function signature with only difference that the other get the param by const is a redefenition?

本文关键字:参数 获取 const 新定义 定义 函数 另一个 有区别 为什么      更新时间:2023-10-16

请考虑以下代码:

#include <iostream>
void f(int t) {
std::cout << 1 << std::endl;
}
void f(const int t) {
std::cout << 2 << std::endl;
}
int main() {
const int i = 5;
f(i);
return 0;
}

我收到以下编译错误:

q2.cpp: In function ‘void f(int)’:
q2.cpp:7:6: error: redefinition of ‘void f(int)’
void f(const int t) {
^
q2.cpp:3:6: error: ‘void f(int)’ previously defined here
void f(int t) {

如果以下内容编译正常,为什么它被认为是重新定义?

#include <iostream>
void f(int& t) {
std::cout << 1 << std::endl;
}
void f(const int& t) {
std::cout << 2 << std::endl;
}
int main() {
int i = 5;
f(i);
return 0;
}

是因为按值发送int会复制它吗?如果是这样,他们是故意这样做的,因为传递价值并使其持续是毫无意义的,还是对 C++11 的限制?

规则是在编译器查看重载时丢弃顶级const限定符。所以f(const int)被视为f(int),这是对前f(int)的重新定义。此规则的原因是,任何可以传递给f(int)的参数也可以传递给f(const int),因为正如您所说,调用会复制值。

这不适用于f(const int&)的原因是这里的const不在顶层。从调用者的角度来看,f(const int&)f(int&)之间的区别在于,例如,当您有const int i = 3;时,您可以将其传递给f(const int&)但不能将其传递给f(int&)