为什么"auto"将字符串声明为const char*而不是std :: string?

Mag*_*nus 9 c++ string auto c++11

我制作了一个模板,用于添加给出的数据.如果我像这样使用它,编译器将in_1和in_2声明为const char*,并且代码不会编译.

#include <iostream>
using namespace std;
template <class T>
T addstuff(T part_1, T part_2){
    return(part_1+part_2);
}

int main(int argc, char const *argv[])
{
    auto in_1="Shut ";
    auto in_2="up.";
    cout<<addstuff(in_1, in_2)<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我声明in_1和in_2 std :: string,它就像一个魅力.

为什么不能(或不)编译器自动声明这些字符串std :: string?

Ale*_*der 7

如果您使用字符串文字,auto将按预期工作。

s在 C++14、C++17 或 C++20 中,您可以在引号后面放置一个,它将创建一个std::string而不是const char*字符串。

这可以与 一起使用auto来创建std::string

auto hello = "hello"s;
Run Code Online (Sandbox Code Playgroud)

默认情况下不启用字符串文字。启用字符串文字的一种方法是将以下内容放置在源文件的顶部:

#include <string>
using namespace std::string_literals;  
Run Code Online (Sandbox Code Playgroud)

例如,此循环适用于std::strings添加到字符串文字),但不适用于const char*类型字符串文字:

for (auto &x : hello) {                                                                        
    std::cout << "letter: " << x << std::endl;                                                         
}
Run Code Online (Sandbox Code Playgroud)

这是""s 运算符的 cppreference 页面。


Yan*_*hof 5

你不能“写”到你的自动变量的原因是它是一个 const char * 或 const char [1],因为这是任何字符串常量的类型。

auto 的重点是解析为最简单的类型,该类型“适用于”分配类型。编译器不会“期待看到你对变量做了什么”,所以它不明白以后你会想要写入这个变量,并用它来存储一个字符串,所以 std::string 会更有意义。

您的代码可以以多种不同的方式工作,以下是一种有意义的方式:

std::string default_name = "";
auto name = default_name;

cin >> name;
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望将第一段中的“字符串常量”更改为“字符串文字”,因为字符串常量可以合理地理解为常量 `std::string`。 (3认同)