在函数内部重新定义函数

Mar*_*kus 12 c++

我偶然发现了一个奇怪的c ++片段.我认为这是错误的代码.为什么有人会在函数内重复函数声明?它甚至在更改类型签名时unsigned int sum(int, int)生成预期结果4294967294j.为什么这甚至编译?

#include <iostream>
#include <typeinfo>

using namespace std;

int sum(int a, int b){
    return a + b;
}

int main()
{
    int sum(int, int); // redeclaring sum???
    int a = -1;
    auto result = sum(a, a);
    cout << result << typeid(result).name() << endl;
}
Run Code Online (Sandbox Code Playgroud)

编辑:它为我编译...但它是有效的C++代码?如果没有,为什么编译器(mingw 4.8.1)允许它?

Vla*_*cow 6

有时在块范围内重新声明函数是有意义的.例如,如果要设置默认参数.请考虑以下代码

#include <typeinfo>

using namespace std;

int sum(int a, int b){
    return a + b;
}

int main()
{
    int sum(int, int = -1 ); // redeclaring sum???
    int a = -1;
    auto result = sum(a, a);
    cout << result << typeid(result).name() << endl;

    result = sum(a);
    cout << result << typeid(result).name() << endl;
}
Run Code Online (Sandbox Code Playgroud)

另一种情况是,您希望从一组重载函数中调用具体函数.请考虑以下示例

#include <iostream>

void g( int ) { std::cout << "g( int )" << std::endl; }
void g( short ) { std::cout << "g( short )" << std::endl; }

int main()
{
   char c = 'c';
   g( c );

   {
      void g( short );
      g( c );
   }
}
Run Code Online (Sandbox Code Playgroud)