在 CPP 中用单个字符初始化字符串
Initializing a string with a single character in CPP
我想用单个字符初始化一个字符串。以下代码不起作用:
int main()
{
string s = 'c';
cout<<s;
return 0;
}
// Result:
error: conversion from ‘char’ to non-scalar type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ requested
string s = 'c';
但下面是。为什么会这样?
int main()
{
string s;
s = 'c';
cout<<s;
return 0;
}
// Output: c[Finished in 0.8s]
当你这样做时
string s = 'c';
你基本上是在调用构造函数初始化而不是赋值操作。但是 std::string
没有任何构造函数只接受一个 char
作为输入。但是有一个 std::string(n, c)
,其中 n
是字符串中的字符数 c
。
当你这样做时
s = 'c'
您执行赋值操作,为 std::string
调用重载的 string::operator=
(string& operator= (char c);
)。现在这个方法被重载以接受单个 char
作为输入,正如你可以从这个 reference as well as at this one.
的代码片段中看到的那样
std::string str1;
// ...
// (4) operator=( CharT );
str1 = '!';
此外,std::string::assign
不接受单个 char
,类似于构造函数。
我想用单个字符初始化一个字符串。以下代码不起作用:
int main()
{
string s = 'c';
cout<<s;
return 0;
}
// Result:
error: conversion from ‘char’ to non-scalar type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ requested
string s = 'c';
但下面是。为什么会这样?
int main()
{
string s;
s = 'c';
cout<<s;
return 0;
}
// Output: c[Finished in 0.8s]
当你这样做时
string s = 'c';
你基本上是在调用构造函数初始化而不是赋值操作。但是 std::string
没有任何构造函数只接受一个 char
作为输入。但是有一个 std::string(n, c)
,其中 n
是字符串中的字符数 c
。
当你这样做时
s = 'c'
您执行赋值操作,为 std::string
调用重载的 string::operator=
(string& operator= (char c);
)。现在这个方法被重载以接受单个 char
作为输入,正如你可以从这个 reference as well as at this one.
std::string str1;
// ...
// (4) operator=( CharT );
str1 = '!';
此外,std::string::assign
不接受单个 char
,类似于构造函数。