C++ redeclaration inconsistency/interestingness

♀尐吖头ヾ 提交于 2019-12-11 14:49:17

问题


I was answering this question when I thought of this example:

#include <iostream>

void func(int i);
void func();

int main (){
    func();
    return 0;
}
void func(){}

In the above example, the code compiles fine. However, in the below example, the code does not compile correctly:

#include <iostream>

void func();
int func();

int main (){
    func();
    return 0;
}
void func(){}

This is the error that occurs when this code is compiled (in clang++):

file.cpp:4:5: error: functions that differ only in their return type cannot be
  overloaded
int func();

I would expect an error like this both times.

I fiddled around with the code a bit, and for some completely odd reason, it seems that the linker completely ignores incorrect declarations. Now this allows for some very weird code. For example this header file would be legal:

#ifndef EXAMPLE
#define EXAMPLE
void func();
void func(int a);
void func(int b);
void func(int a, int b);
void func(int a, short b);
void func(int w);
void func(short b);
#endif

Why? Why in the world does any of this work? Is this just a C++ standard failure? Compiler failure? "Feature"? Actual Feature? (That is all one question by the way.)

P.S. While I'm waiting for an answer, I'm going to be over here taking advantage of this for pre-adding features in code that will probably end up in production.


回答1:


The first is function overload, argument names are not taken into account (argument types or its count are different).

The second is function redeclaration (argument types and count are the same) with changed return type that is forbidden. Overloading of return type only is not allowed. The compiler told it to you.



来源:https://stackoverflow.com/questions/49205371/c-redeclaration-inconsistency-interestingness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!