這個程序被稱爲localFunc.c文件中:本地(塊)函數decln與defn返回類型不匹配;診斷在C++?
#include <stdio.h>
// int f(int); // Global forward declaration.
int main() {
int f(int); // Local forward declaration.
printf("%d\n", f(1));
}
double f(int i) {
return 1.0;
}
通過gcc localFunc.c
編譯給出:
localFunc.c:10:8: error: conflicting types for ‘f’
double f(int i) {
^
localFunc.c:6:7: note: previous declaration of ‘f’ was here
int f(int); // Local forward declaration.
但通過g++ localFunc.c
編譯,沒有任何錯誤和運行可執行文件的結果: 4195638
。
註釋掉本地前向聲明,並打開全局前向聲明:int f(int);
,gcc和g ++都給出了與上面類似的錯誤,正如我所預料的那樣。
所以我的問題是,爲什麼g ++看不到本地聲明函數中的衝突類型(模糊聲明)?
[email protected]:~/UNIX/CS213$ gcc --version
gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
是不是像C和C++是不同的語言? –
@Leushenko但你不能僅基於返回類型進行重載。另外,由於文件名,g ++可能會將代碼編譯爲C.無論哪種方式,它都不應該編譯。 – juanchopanza
如果您想使用printf,請確保您傳遞正確的格式字符串。在這種情況下,我猜測使用了全局重載,所以應該使用'%lf'而不是'%d'。然而,我會推薦'std :: cout << f(1)<< std :: endl;' 請注意,gcc確實注意到這種不一致性,並告訴你它會遇到問題,很可能在1.0版本中會出現reinterpret_cast到int – JVApen