【问题标题】:Why I can't define a static field in the declaration? [duplicate]为什么我不能在声明中定义静态字段? [复制]
【发布时间】:2021-02-11 22:16:17
【问题描述】:

所以看起来我由于某种原因不能这样做......

class MyClass
{
    static std::string name = "Whatever";
};

我不明白,对我来说,在声明中定义一些东西是有意义的,即使是静态的,但相反,我必须这样做...... ¿?¿?¿?

class MyClass
{
    static std::string name;
};
std::string MyClass::name = "Whatever";

顺便说一句... name 默认不是私有的吗?那为什么我可以从类外改变它的值呢?

【问题讨论】:

标签: c++


【解决方案1】:

为什么我不能在声明中定义静态字段?

你可以!

#include <string>

class MyClass
{
    static inline std::string name = "Whatever";
    //     ^^^^^^
};

默认情况下名称不是私有的吗?那为什么我可以从类外改变它的值呢?

你不能!

您正在定义/初始化它,而不是更改它的值。

【讨论】:

  • 不,我不能,它说“不能将非静态数据成员声明为内联”
  • @Karlos 那么你的编译器是古老的,或者设置为古老的模式。它是什么以及您使用的是什么标准?
  • 我正在使用 Visual Studio 2019
  • 等等……“非静态”??
猜你喜欢
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 2013-03-05
  • 2015-09-11
  • 2010-09-06
  • 1970-01-01
  • 2011-04-04
相关资源
最近更新 更多