定义具有不同签名的函数 [英] Defining a function with different signature

查看:120
本文介绍了定义具有不同签名的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我发现有可能在一个标记中声明一个函数,并在源文件中用不同的(类似的)签名实现它。例如,像这样:

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

这是允许的吗?或者是编译器的扩展(我使用g ++ 4.3.0)?

Is this allowed? Or is this the compiler's extension (I am using g++ 4.3.0) ?

EDIT
我正在编译与pedantic和最大

EDIT I am compiling with pedantic and maximum possible warning level, and I am still not getting a warning or an error.

推荐答案

为了确定函数签名的目的,将忽略任何顶级 const 限定符。这是因为它不会影响函数调用者。函数参数在任何情况下都通过值传递,所以函数不会影响传入的参数。

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.

顶层 const 确实影响函数的主体。它确定参数是否可以在函数体中更改。它与声明的功能相同。

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.

标准引用:8.3.5 [dcl.fct] / 3:[...]函数的类型使用以下规则确定[...] em ... cv-qualifiers 修改参数类型[...]这样的 cv-qualifiers 只影响函数体内参数的定义;它们不影响函数类型。[...]

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. [...]"

这篇关于定义具有不同签名的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆