在c++ 11中初始化C -string

Initialize a c-string in C++11?

本文关键字:-string 初始化 c++      更新时间:2023-10-16

如何在c++ 11中初始化C -string ?

I tried:

char* foo = {"bar"};

但是我得到:

ISO C++11 does not allow conversion from string literal to 'char *

因为它必须是指向const的指针:

const char* foo = "bar";

在c++ 11之前,您可以将foo简化为char*,尽管自c++ 03以来已弃用。但是c++ 11删除了弃用,并使其成为非法的。

正确的做法是;

char const* foo = {"bar"};
//   ^^^^^ added const

旧的C风格(非const)已被弃用,现在从c++ 11中删除。

相关文章: