c++ - 为什么函数声明在 C++ 中可以有 const 参数?

标签 c++

考虑以下函数声明:

void foo(const int);

此函数具有签名 void(int)。可以定义如下:

void foo(int) {}

这是有道理的,因为参数在函数体内是否为 const 对调用者来说并不重要。 但是,为什么我们甚至允许在函数声明中写入 const 参数?

编辑:这不是 this question 的拷贝.在那个问题中,const 被添加到函数定义的参数中。他们没有在函数声明中讨论 const 参数。

最佳答案

就C++语言而言,这两个声明是完全等价的:

void foo(const int);
void foo(int);

引用 C++11 ( latest public draft ) 标准,第 13.1 节“可重载声明”:

Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called. Example:

typedef const int cInt;
int f (int);
int f (const int);                // redeclaration of f(int)
int f (int)  { /* ...  */ }       // definition of f(int)
int f (cInt) { /* ...  */ }       // error: redefinition of f(int)

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.124 In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”


124 When a parameter type includes a function type, such as in the case of a parameter type that is a pointer to function, the const and volatile type-specifiers at the outermost level of the parameter type specifications for the inner function type are also ignored.

因此,允许函数声明具有const 参数的原因是因为标准规定它们等同于具有非const 参数的函数声明。

不用说,这意味着您不能根据参数的 cv 限定重载函数。

const 类型说明符仅在函数的定义 中起作用,它防止对该参数进行局部修改。

我想没有人能想出一个很好的理由来引入额外的复杂性,这将需要禁止 const(和volatile)在声明中,当它们被允许并且在定义中很重要时。

关于c++ - 为什么函数声明在 C++ 中可以有 const 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44483076/

相关文章:

c++ - 适用于 Windows 的 Helgrind?

c++ - 将派生类转换为具有相同公共(public)函数的泛型类类型,同时仍然可以调用派生类的函数

c++ - Qt QLabel setPixmap 不需要的填充

c++ - TLS 变量访问的结果未缓存

c++ - 大阶乘系列

c++ - 运行 Ubuntu 12.04 64 位的目标嵌入式计算机是否支持 Qt for Embedded Linux?

c++ - 渲染具有透明度的纹理时 OpenGL 不需要的像素

c++ - 如何结束 C++ 代码

c++ - 猫文件名 | command 和 command < filename 表现不同

c++ - 如何删除指向动态分配对象的智能指针?