我无法在底部编译代码。我一直在C
执行此操作,但在C++
内的某个类中无法执行此操作。有人可以告诉我这里有什么问题吗?
class Parser {
struct table {
string first;
string second;
string third;
} c_table [] = {
"0","a","b",
"0","c","d",
"0","e","f",
};
};
int main() {
return 0;
}
test.cpp:22:3: error: too many initializers for ‘Parser::table [0]’
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"a"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"b"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"c"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"d"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"e"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"f"’ from ‘const char*’ to ‘Parser::table’
答案 0 :(得分:7)
Pre-C ++ 11你不允许在类定义中初始化成员(整数类型的static const
成员除外)。除了将它填充到构造函数体内之外,别无选择。
在C ++ 11中,您可以使用初始化程序,但
#include <string>
using std::string;
class Parser {
struct table {
string first;
string second;
string third;
} c_table [3] = {
{"0","a","b"}, // <-- note the braces
{"0","c","d"},
{"0","e","f"}
};
};
我认为你需要指定维度的原因是因为类定义中的初始化程序可以被某个构造函数中的成员初始化程序所取代,这可能具有不同的元素数。