expected ‘,’ or ‘...’ before string constant

Viewed 5279

Why const std::string str="__$HOOK_FUNC_FOR_LUA_KEY@__"; is ok whereas the compiler complains when compiling

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

NOTE: str is a member variable of a C++ class.

Demo code:

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

Here are the the error messages:

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

It's obvious that there is ctor for std::string(char*). So I am really confused.

2 Answers

You can't have function-like inittialization inline in classes. You must use curly-braces {} or "assignment" like syntax with =.

It's a way to go around the problem of detecting if you're declaring a function or a variable.

And as you're dealing with std::string which has an std::initializer_list constructor (which will be used for curly-brace initialization) you can only use assignment-like syntax:

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

Of course, you can use a constructor initializer list as well:

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