为什么带有const参数的函数声明允许调用带有非const参数的函数?

编程入门 行业动态 更新时间:2024-10-25 13:31:03
本文介绍了为什么带有const参数的函数声明允许调用带有非const参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请注意以下C ++代码:

#include< iostream> using std :: cout; int foo(const int); int main() { cout< foo(3); } int foo(int a) { a ++; return a;注意, foo()的原型 code>接受一个 const int ,定义接受 int 。这个编译没有任何错误...

为什么没有编译错误?

解决方案

因为 foo 函数的调用者是否 foo 修改其副本

特别是在C ++ 03标准中,以下2个代码段解释了为什么:

C ++ 03 Section:13.2-1

同名的两个函数声明相同的函数,如果他们在同一范围和有等效参数声明(13.1)。

C + +03 Section:13.1-3

参数声明仅在const和/当量。只有在参数类型规范的最外层的const和volatile类型说明符以这种方式被忽略;隐藏在参数类型规范中的const和volatile类型说明符是重要的,可用于区分重载函数声明。

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; }

Notice that the prototype of foo() takes a const int and that the definition takes an int. This compile without any errors...

Why are there no compilation errors?

解决方案

Because it doesn't matter to the caller of the foo function whether foo modifies its copy of the variable or not.

Specifically in the C++03 standard, the following 2 snippets explain exactly why:

C++03 Section: 13.2-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 Section: 13.1-3

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参数的函数?

本文发布于:2023-07-21 11:07:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1176905.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   声明   const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!