任何人都可以告诉我这个程序中的错误
#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."
答案 0 :(得分:11)
有两个名为toupper
的函数。一个来自cctype
标题:
int toupper( int ch );
来自locale
标题的第二个:
charT toupper( charT ch, const locale& loc );
编译器无法推断出应该使用哪个函数,因为您允许使用名称空间std
。您应该使用范围解析运算符(::
)来选择在全局空间中定义的函数:
transform(str.begin(), str.end(), str.begin(), ::toupper);
或者,更好:不要使用using namespace std
。
感谢@Praetorian -
这可能是导致错误的原因,但添加
::
并非总是如此 工作。如果您包含cctype
toupper
,则不保证存在 全局命名空间演员可以提供必要的消歧static_cast<int(*)(int)>(std::toupper)
所以,调用应该如下:
std::transform
(
str.begin(), str.end(),
str.begin(),
static_cast<int(*)(int)>(std::toupper)
);
答案 1 :(得分: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));
中的示例代码
或者您可以实现自己的toupper
以char
作为参数。
答案 2 :(得分:0)
由于编译器已经隐藏在其错误消息中,真正的问题是toupper是一个重载函数,编译器无法找出你想要的那个。有一个C toupper(int)函数,它可能是也可能不是一个宏(可能不是在C ++中,但C库是否关心?),并且有std :: toupper(char,locale)(毫无疑问地被拉入) ,您使用using namespace std;
在全球范围内提供。
托尼的解决方案有效,因为他意外地通过单独的功能解决了超载问题。