【问题标题】:VS2010 only static const integral data members can be initialized within a classVS2010 只有静态 const 整数数据成员可以在类内初始化
【发布时间】:2012-08-14 15:03:50
【问题描述】:

最近有人告诉我,Windows Visual Studio 是用于 C++ 开发的最佳 IDE 之一,所以我决定购买它,但这是我第一次使用它,而且我已经遇到了一个奇怪的错误。以下代码:

#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;

class Player {
public:
    string name = "Player";
};

int main() {
    cout << "Works";
    return 0;
}

返回错误 C2864: 'Player::name' : 只有静态 const 整数数据成员可以在类中初始化。怎么了?此代码在 Codeblocks IDE 中编译。请向我解释我不明白的问题。

【问题讨论】:

  • @RobertoWilko 该列表中此功能的名称是什么?我没有看到任何说明 VS2010 是否支持此功能。
  • @DavidDoria - 排名第三。 Non-static data member initializers 不幸的是,似乎 VS 在采用所有这些方面实际上有点慢。

标签: c++ visual-studio-2010 compiler-errors


【解决方案1】:

在 C++03 中,不能在声明点初始化数据成员。您可以在构造函数中执行此操作。

class Player {
public:
    Player() : name("Player") {}
    string name;
};

在 C++11 中,您的代码很好,因此可能是您在 Codeblocks 中使用 C++11 支持进行编译。

【讨论】:

  • 谢谢,这很奇怪,我可以让 VS2010 在 C++11 中编译吗?
  • @ThePlan 显然是there is some support。但是我没有用VS,所以不知道怎么开启。
  • Piggy 问题:这会导致在实例化之前分配内存吗?我的意思是 C++11 标准。
  • @RobertoWilko 数据成员的分配发生在 Player 对象被实例化时。这相当于使用构造函数初始化列表。
【解决方案2】:
class Player {
public:
    string name = "Player";
};

此语法已在 C++11 中引入。在 MSVC 支持的 C++03 标准的早期版本中,它应该如下所示:

class Player {
public:
    Player() : name("Player") {}
    string name;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2014-03-31
    相关资源
    最近更新 更多