【问题标题】:Why the following code doesn't compile in MSVC and does in g++?为什么下面的代码不能在 MSVC 中编译而在 g++ 中编译?
【发布时间】: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


【解决方案1】:

该语法是非标准的 GNU 扩展,因此不受任何版本的 Microsoft Visual C++ 支持(并且可能永远不会)。

指定初始化器在 C++20 中已标准化,但语法不同,它们仅可用于聚合初始化。等效的标准指定初始化器语法为Spell{.name = "test", .action = "lol"}。不过在这种情况下也行不通,因为Spell 不是聚合,因为它具有私有数据成员和用户定义的构造函数。

【讨论】:

  • 您好先生,感谢您的回答。我还发现了这个tldp.org/LDP/lkmpg/2.4/html/c577.htm,但就我而言,它只是调用构造函数,与字段无关。以下代码编译成功:class Spell { public: Spell(std::string name, std::string action) {} }; int main() { Spell * spell = new Spell{ name : "test", action : "lol" }; }
猜你喜欢
  • 2019-11-15
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 2017-07-09
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多