【发布时间】:2021-04-04 22:20:11
【问题描述】:
我正在尝试在 main 中使用带有冒号的构造函数初始值设定项列表,但它无法在 Microsoft Visual Studio 2019 中编译(错误:标识符“名称”未定义且预期为“}”) ,但它在 Linux 中的 g++(版本 10.2.0)中编译和打印输出没有任何问题。
我也尝试了不同版本的 MSVC,比如 C++14、C++17,但没有结果。 我知道 C++11 的所有可能的初始化,但我必须使用带有冒号(:)的初始化。
有没有办法在 MSVC 中做到这一点?
提前致谢!
#include <string>
#include <iostream>
class Spell {
private:
std::string name;
std::string action;
public:
Spell(std::string name, std::string action) : name(name), action(action) {}
void print() {
std::cout << name;
}
};
int main() {
Spell* spell = new Spell{ name : "test", action : "lol" }; //HERE
spell->print();
}
【问题讨论】:
-
用 -
pedantic编译 gcc 中的代码,你会看到类似 * 警告:ISO C++ 不允许 GNU 指定的初始化程序*。如果您想要可移植性,则必须使用符合标准的代码。
标签: c++ visual-c++ g++ c++20 initializer-list