#include <iostream>
using namespace std;
void somefunc(int a)
{
cout<<"somefunc1";
}
void somefunc(int &b)
{
cout<<"somefunc2";
}
int main()
{
// case 1
somefunc(10); // works fine and prints somefunc1
//case2
int b=10;
somefunc(b); // generates compiler error that overloading is ambiguous
return 0;
}
在main()
如果我通過一個常數(比如說10
)程序編譯和運行並打印"somefunc1"
,但是當我傳遞變量(b
在這種情況下)編譯器產生一個錯誤超載是不明確的。函數重載 - 傳遞恆定VS傳遞變量C++
我不明白它是如何在內部工作的。 請幫忙!!
這是因爲綁定到引用是一個「完全匹配」,所以重載是不明確的。 –
你稱之爲*「常量」*稱爲*「整數字面量」*。傳遞常量(例如'const int c = 10;')會產生不同的結果。爲什麼傳遞'c'與傳遞'b'不同,這是對讀者的一個練習。 – IInspectable
@IInspectable:你的常數[也可以正常工作](http://ideone.com/NbWeSW)。 –