2013-05-28 61 views
4

誰能告訴我什麼是在這個程序中的錯誤沒有匹配函數調用「改造

#include <iostream> 
#include <algorithm> 

using namespace std; 

int main() 
{ 
    string str = "Now"; 

    transform(str.begin(), str.end(), str.begin(), toupper); 

    cout<<str; 

    return 0; 
} 

錯誤:

"no matching function for call to 'transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)' 
compilation terminated due to -Wfatal-errors." 
+2

試試......,:toupper);' –

+0

嘗試'#include '然後'std :: ctype :: toupper'作爲參數。 –

+0

當您處理錯誤時,您無法弄清楚,因爲該開關可以抑制相關信息,所以編譯時可能不會出現'-Wfatal-errors'錯誤。 – Praetorian

回答

9

沒有與名稱toupper兩種功能。一位來自cctype頭:從locale

int toupper(int ch); 

其次:

charT toupper(charT ch, const locale& loc); 

編譯器不能推斷應該使用哪些功能,因爲您允許的命名空間std。您應該使用範圍解析操作::)選擇在全局空間定義函數:

transform(str.begin(), str.end(), str.begin(), ::toupper); 

或者,更好:不要使用using namespace std


感謝@Praetorian -

This is probably the cause of the error, but adding :: may not always work. If you include cctype toupper is not guaranteed to exist in the global namespace. A cast can provide the necessary disambiguation static_cast<int(*)(int)>(std::toupper)

因此,調用應該是這樣的:

std::transform 
(
    str.begin(), str.end(), 
    str.begin(), 
    static_cast<int(*)(int)>(std::toupper) 
); 
+1

這可能是錯誤的原因,但添加'::'可能並不總是有效。如果包含* cctype *'toupper'不能保證存在於全局命名空間中。演員可以提供必要的消歧'static_cast (std :: toupper)' – Praetorian

+0

@Praetorian,是的,你是對的,謝謝。 – soon

+0

是的懂了 非常感謝 – user2413497

2

爲了使用toupper,你需要包含頭文件:

#include <cctype> 

您還需要包含頭文件:

#include <string> 

的問題是std::toupper需要int作爲參數,而std::transform將通過char進入的功能,因此,它有一個問題(由@juanchopanza提供)。

你可以嘗試使用:

#include <functional> 
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper)); 

std::transform

見示例代碼或者,你可以實現自己的toupper這需要char作爲參數。

+0

我包括但是沒用的 – user2413497

+0

@ user2413497試着檢查我收錄的鏈接?它在鏈接底部有解釋的完整例子。 – taocp

+0

@juanchopanza我同意。我現在將更新該帖子。 – taocp

0

由於編譯器埋藏在它的錯誤信息中,真正的問題是toupper是一個重載函數,編譯器無法弄清楚你想要哪一個。 C toupper(int)函數可能是也可能不是宏(可能不在C++中,但是C庫在意嗎?),並且std :: toupper(char,locale)來自(毫無疑問地被引入) ,您可以通過using namespace std;在全球範圍內使用。

託尼的解決方案的工作原理是因爲他意外地用他的單獨函數解決了超載問題。