小编Ale*_*exP的帖子

为什么以下代码不能在 MSVC 中编译而在 g++ 中可以?

我正在尝试在 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();
}
Run Code Online (Sandbox Code Playgroud)

c++ g++ initializer-list visual-c++ c++20

2
推荐指数
1
解决办法
96
查看次数

标签 统计

c++ ×1

c++20 ×1

g++ ×1

initializer-list ×1

visual-c++ ×1