Alb*_*ieu -1 c++ string char casing implicit-conversion
我只是好奇相同的类型转换格式适用于 char、int 以及其他许多类型,但为什么它不适用于字符串,即(string) 'c'屏幕后面出了什么问题?
#include <iostream>
using namespace std;
int main(){
char a = 'a';
cout << (char) 99 <<endl;
cout << (int) 'c'<<endl;
cout<< (string) 'c' + "++" <<endl; // why this does not work???
cout<< string (1, 'c') + "++" <<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是没有从 类型的对象char到 类型的对象的隐式转换std::string。
例如你可以这样写:
cout<< string( 1, 'c' ) + "++" <<endl;
Run Code Online (Sandbox Code Playgroud)
或者
cout<< string( "c" ) + "++" <<endl;
Run Code Online (Sandbox Code Playgroud)
或(使用 C 铸造)
cout<< ( string )"c" + "++" <<endl;
Run Code Online (Sandbox Code Playgroud)
或者
using namespace std::literals;
cout << "c"s + "++" << endl;
Run Code Online (Sandbox Code Playgroud)
从这一行你可以看到
cout<< string( 1, 'c' ) + "++" <<endl;
Run Code Online (Sandbox Code Playgroud)
这里使用了构造函数
basic_string(size_type n, charT c, const Allocator& a = Allocator());
Run Code Online (Sandbox Code Playgroud)