9 79 D:\dev c++\cifa2.cpp [Error] in C++98 'grammar' must be initialized by constructor, not by '{...}'
时间: 2023-12-10 12:39:29 浏览: 73
C++编译出现的错及修正
这个错误提示是因为在 C++98 标准中,类的成员变量不能使用花括号来初始化,而必须使用构造函数。比如下面的代码就会导致这个错误:
```cpp
class Grammar {
public:
std::vector<std::string> nonterminals {"S", "A", "B", "C"};
std::vector<std::string> terminals {"a", "b", "c", "d", "e", "f"};
std::unordered_map<std::string, std::vector<std::vector<std::string>>> rules {
{"S", {{"A", "B", "C"}}},
{"A", {{"a", "A"}, {"b"}}},
{"B", {{"c", "B"}, {"d"}}},
{"C", {{"e", "C"}, {"f"}}}
};
};
```
解决这个问题的方法是,使用构造函数来初始化成员变量,例如:
```cpp
class Grammar {
public:
Grammar()
: nonterminals{"S", "A", "B", "C"},
terminals{"a", "b", "c", "d", "e", "f"},
rules{
{"S", {{"A", "B", "C"}}},
{"A", {{"a", "A"}, {"b"}}},
{"B", {{"c", "B"}, {"d"}}},
{"C", {{"e", "C"}, {"f"}}}
}
{}
std::vector<std::string> nonterminals;
std::vector<std::string> terminals;
std::unordered_map<std::string, std::vector<std::vector<std::string>>> rules;
};
```
这样就可以在 C++98 标准下正常编译了。当然,在 C++11 之后,使用花括号初始化成员变量是被允许的,所以如果你使用的是较新的编译器,也可以直接使用花括号初始化成员变量。
阅读全文