为什么相同的函数签名只有区别,另一个通过 const 获取参数是重新定义?
Why same function signature with only difference that the other get the param by const is a redefenition?
请考虑以下代码:
#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&)
。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 有没有办法在从编译器获取参数时避免预处理器宏?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 如何从参数中获取函数签名?
- 获取可变参数模板参数包的相关类型
- 在 C++11 中获取函子作为参数
- 如何使用可变参数模板获取参数的变量号及其大小C++
- 是否可以获取成员函数模板参数的拥有对象?
- 如何从 x64 程序集中的堆栈中获取参数?
- 获取第一个模板参数的可靠方法
- 如何从参数包获取指向对象的指针
- C++ 如何使派生类自动获取基类参数
- 通过命令行参数获取llvm ir文件时面临问题
- 在C++中,是否允许将函数指针强制转换为将指向基类或派生类的指针作为参数获取的函数指针
- 使用一个可选参数获取两个参数到main
- cpp 映射作为函数参数获取警告信息 "discards qualifiers"
- 从控制台应用中的命令行参数获取文件名C++
- 从模板参数获取函数参数
- 使用参数获取其他参数