Why does a function declaration with a const argument allow calling of a function with a non-const argument?(为什么带有 const 参数的函数声明允许调用带有非常量参数的函数?)
问题描述
注意以下 C++ 代码:
Take note of the following C++ code:
#include <iostream>
using std::cout;
int foo (const int);
int main ()
{
cout << foo(3);
}
int foo (int a)
{
a++;
return a;
}
请注意,foo()
的原型采用 const int
并且定义采用 int
.这个编译没有任何错误...
Notice that the prototype of foo()
takes a const int
and that the definition takes an int
. This compile without any errors...
为什么没有编译错误?
推荐答案
因为对于 foo
函数的调用者来说,foo
是否修改其副本并不重要变量与否.
Because it doesn't matter to the caller of the foo
function whether foo
modifies its copy of the variable or not.
特别是在 C++03 标准中,以下 2 个代码段准确解释了原因:
Specifically in the C++03 standard, the following 2 snippets explain exactly why:
C++03 部分:13.2-1
如果两个同名的函数声明在同一个作用域内,则它们引用同一个函数具有等效的参数声明 (13.1).
Two function declarations of the same name refer to the same function if they are in the same scope and have equivalent parameter declarations (13.1).
C++03 部分:13.1-3
仅在存在或不存在 const 和/或 volatile 时不同的参数声明是等效的.以这种方式仅忽略参数类型规范最外层的 const 和 volatile 类型说明符;埋在参数类型规范中的 const 和 volatile 类型说明符很重要,可用于区分重载的函数声明.
Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.
这篇关于为什么带有 const 参数的函数声明允许调用带有非常量参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么带有 const 参数的函数声明允许调用带有非常量参数的函数?


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01