定义具有不同签名的函数
今天我发现可以在标头中用一个签名声明一个函数,并在源文件中用不同(相似)的签名实现它。例如,像这样:
// THE HEADER example.hpp
#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP
int foo( const int v );
#endif
// THE SOURCE FILE example.cpp
#include "example.hpp"
int foo( int v ) // missing const
{
return ++v;
}
这是允许的吗?或者这是编译器的扩展(我使用的是 g++ 4.3.0)?
编辑 我正在以迂腐和最大可能的警告级别进行编译,但我仍然没有收到警告或错误。
Today I discovered that it is possible to declare a function in a header with one signature, and implement it in the source file with different (similar) signature. For example, like this :
// THE HEADER example.hpp
#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP
int foo( const int v );
#endif
// THE SOURCE FILE example.cpp
#include "example.hpp"
int foo( int v ) // missing const
{
return ++v;
}
Is this allowed? Or is this the compiler's extension (I am using g++ 4.3.0) ?
EDIT
I am compiling with pedantic and maximum possible warning level, and I am still not getting a warning or an error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了确定函数签名,任何顶级
const
限定符都会被忽略。这是因为它不影响函数调用者。在任何情况下,函数参数都是按值传递的,因此函数不会影响传入的参数。顶级
const
确实会影响函数体。它确定函数体内的参数是否可以更改。但它与声明的功能相同。所以是的,它是合法的,并且声明和定义引用相同的函数而不是重载。
标准参考:8.3.5 [dcl.fct] / 3:“[...]函数的类型使用以下规则确定。[...]任何cv-qualifier修改[...]此类cv限定符仅影响函数体内参数的定义;它们不影响函数类型。
For the purposes of determining a function signature, any top level
const
qualifier is ignored. This is because it does not affect function callers. Function parameters are passed by value in any case so the function cannot affect the arguments passed in.The top level
const
does affect the body of the function. It determines whether or not the parameter can be changed in the body of the function. It is the same function as the declaration though.So yes, it is legal and the declaration and definition refer to the same function and not an overload.
Standard reference: 8.3.5 [dcl.fct] / 3: "[...] The type of a function is determined using the following rules. [...] Any cv-qualifier modifying a parameter type is deleted. [...] Such cv-qualifiers affect only the definition of the parameter within the body of the function; they do not affect the function type. [...]"
由于 int 是基本值类型,因此 const 修饰符在这里没有任何作用。无论你在函数中对 int 做什么,调用者都不会看到它。
您无法使用 int& 执行此操作。在这种情况下,const 的存在或不存在确实与调用者相关,因为引用的 int 可以被修改。
Since int is a basic value type, the const modifier does not have any effect here. No matter what you do to your int in the function, this will never be seen by the caller.
You can't do this with int&. In that case, the presence or absence of const is really relevant for the caller, since the int referred to could be modified.