我在使用 toupper() 函数时遇到问题:
Code :
#include <iostream>
#include <string>
using namespace std;
int main (){
string input {"ab"};
string output {""};
cout << output + toupper(input[0]);
return 0;
}
the error is :
没有运算符“+”与这些操作数匹配 - 操作数类型为: std::_cx11::string + int 。
但如果我写:
#include <iostream>
#include <string>
using namespace std;
int main (){
string input {"ab"};
string output {""};
char temp = toupper(input[0]);
cout << output + temp;
return 0;
}
效果很好。谁能告诉我为什么吗?
toupper的返回值是int
,并且您不能添加std::string
and an int
由于没有现有的operator+(int)
. Your char temp
隐式转换int
返回值到char
在其初始化期间,并且从那时起std::string
has an operator+(char)
过载,这有效。尽管您可以使用以下命令复制相同的行为static_cast
反而:
cout << output + static_cast<char>(toupper(input[0]));
作为旁注,ctype
函数通常是一个期望值,可表示为unsigned char
, or EOF
,要通过,所以你应该转换char
论点unsigned char
在经过他们之前。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)