doo*_*ogy 3 c++ class declaration stdvector
例如:
struct Spell
{
int id;
vector<int> cost(4);
};
Run Code Online (Sandbox Code Playgroud)
它说
'Expected parameter declaration'.
Run Code Online (Sandbox Code Playgroud)
另外这段代码有什么区别吗?
if (can(vector <int>inv, spell.cost))
{
cout << "CAST " << spell.id << endl;
done = true;
break;
}
Run Code Online (Sandbox Code Playgroud)
这个说
'Expected '(' for function-style cast or type construction'
Run Code Online (Sandbox Code Playgroud)
有机会可以帮我一下吗?
正如cppreference.com中的成员初始化部分所述:
\n\n\n非静态数据成员可以通过以下两种方式之一进行初始化:
\n\n
\n- \n
在构造函数的成员初始值设定项列表中。
\nRun Code Online (Sandbox Code Playgroud)\nstruct S\n{\n int n;\n std::string s;\n S() : n(7) {} // direct-initializes n, default-initializes s\n};\n- \n
通过默认成员初始值设定项,它是包含在成员声明中的大括号或等于初始值设定项,如果从构造函数的成员初始值设定项列表中省略该成员,则使用该成员初始值设定项。
\nRun Code Online (Sandbox Code Playgroud)\nstruct S\n{\n int n = 7;\n std::string s{ \'a\', \'b\', \'c\' };\n S() {} // default member initializer will copy-initialize n, \n // list-initialize s\n};\n
根据上述(强调我的),您的会员声明是错误的。
\nint我假设,您的意图是拥有s (即)向量cost作为成员并分配4整数并默认(值)初始化它们。
您可以通过以下任一方式修复:
\nstruct Spell {\n int id;\n std::vector<int> cost{ std::vector<int>(4) };\n // ^^^ ^^^^\n};\nRun Code Online (Sandbox Code Playgroud)\nstruct Spell {\n int id;\n std::vector<int> cost = std::vector<int>(4); // or decltype(cost)(4)\n // ^^^^^^^^^^^^^^^^^^^^^^^^\n};\nRun Code Online (Sandbox Code Playgroud)\nstruct Spell { \n int id; \n std::vector<int> cost;\n Spell()\n : cost(4) // constructor member initializer\n {} \n};\nRun Code Online (Sandbox Code Playgroud)\n\xe2\x9c\xb1由于std::vector 有std::initializer_list构造函数,不幸的是你不能写std::vector<int> cost{ 4 },因为它将被解释4为单个向量元素。