我學習新的C++語法,我得到了這個程序中的錯誤:呼叫超載是ambigious
#include <iostream>
#include <string>
#include <utility>
std::string foo(std::string str)
{
return str + " call from normal";
}
std::string foo(const std::string& str)
{
return str + " call from normal";
}
std::string foo(std::string&& str)
{
return str + " call from ref ref";
}
int main()
{
std::string str = "Hello World!";
std::string res = foo(str);
std::string&& res_ref = foo(std::move(str));
std::cout << "Res ref = " << res_ref << std::endl;
std::cout << "Str = " << str << std::endl;
return 0;
}
的錯誤是:
:23:30: error: call of overloaded ‘foo(std::__cxx11::string&)’ is ambiguous std::string res = foo(str);
爲什麼呼叫曖昧?
你有3個'foo'函數,它不能確定你想使用哪一個函數。 – Carcigenicate
但它的雙引用,標準函數和const ref,爲什麼會發生這個問題?當我評論第一個函數聲明一切工作正常,我的問題是:爲什麼編譯器不能選擇一個人使用? – Asmozan
編譯器應該如何知道是否要調用'std :: string foo(std :: string str)'或'std :: string foo(const std :: string&str)'?你可以用完全相同的方式調用它們。 – UnholySheep