字符串常量前的预期','或'…'

为什么const std::string str="__$HOOK_FUNC_FOR_LUA_KEY@__";可以,而编译器在编译时会抱怨

const std::string str("__$HOOK_FUNC_FOR_LUA_KEY@__");?

注意str是 C++ 类的成员变量。

演示代码:

class Demo
{
private:
const std::string str("__$HOOK_FUNC_FOR_LUA_KEY@__");
}

以下是错误消息:

test.hpp:253:51: error: expected identifier before string constant
     const std::string str("__$HOOK_FUNC_FOR_LUA_KEY@__");
                                                   ^
test.hpp:253:51: error: expected ‘,’ or ‘...’ before string constant

很明显,有 ctor for std::string(char*)。所以我真的很困惑。

回答

你不能在类中内联类似函数的初始化。您必须使用花括号{}或“赋值”之类的语法与=.

这是一种绕过检测您是在声明函数还是变量的问题的方法。

而当你正在处理std::string它有一个std::initializer_list构造函数(这将被用于大括号初始化),你只能使用指定的语法:

const std::string str = "__$HOOK_FUNC_FOR_LUA_KEY@__";

当然,您也可以使用构造函数初始化列表:

Demo()
    : str("__$HOOK_FUNC_FOR_LUA_KEY@__")
{}


以上是字符串常量前的预期','或'…'的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>