【问题标题】:Initializing a string with a single character in CPP在 CPP 中使用单个字符初始化字符串
【发布时间】:2021-01-11 15:02:49
【问题描述】:

我想用单个字符初始化一个字符串。以下代码不起作用:

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" 工作!
  • the constructor 没有一个接受一个字符,而operator= 有一个。我不知道为什么。
  • @NathanOliver 目标错误。 OP 不是要求修复,而是为什么分配有效而不是初始化。我要重新营业了。
  • string s = 'c'; --> string s(1, 'c');

标签: c++ string initialization character


【解决方案1】:

当你这样做时

string s = 'c';

您基本上是在调用构造函数初始化而不是赋值操作。但是没有任何 std::string 的构造函数只接受一个 char 作为输入。但是有一个std::string(n, c),其中n 是字符串中c 的字符数。

当你这样做时

s = 'c'

您执行赋值操作,为std::string 调用重载的string::operator= (string&amp; operator= (char c);)。现在,此方法已重载以接受单个 char 作为输入,正如您从 reference 和 this 的代码 sn-p 中看到的那样。

std::string str1;
// ...
// (4) operator=( CharT );
str1 = '!'; 

此外,std::string::assign 不接受单个 char,类似于构造函数。

【讨论】:

    猜你喜欢
    • 2015-09-16
    • 1970-01-01
    • 2017-05-02
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    相关资源
    最近更新 更多