使用字符串字符数组初始化字符串时出错?

开发者05

我正在尝试初始化这个字符串 s1 但我不知道为什么我会收到这个错误,这可能是由于 s[0] 是字符,但是为什么当我初始化并声明相同的字符串 s1 但在不同的行中时一切都变好了,一个其他。

#include <bits/stdc++.h>

int main()
{
  std::string s = "text";
  std::string s1 = s[0];

  std::cout << s1;
}

错误:

 error: conversion from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' 
 {aka 'char'} to non-scalar type 'std::__cxx11::string' {aka 
 'std::__cxx11::basic_string<char>'} requested
 std::string s1 = s[0];
                    ^

这工作正常:

#include <bits/stdc++.h>

int main()
{
  std::string s = "text";
  std::string s1;
  s1 = s[0];

  std::cout << s1;
}
P0W

char没有构造函数有一个复制分配,适用于第二个片段。

但是,你可以这样写

std::string s1 ( 1, s[0] );

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章