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

标签 c++

<分区>

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

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

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

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

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

最佳答案

Why I can't define a static field in the declaration?

你可以!

#include <string>

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

Isn't name private by default? Then why can I change its value from outside the class?

你不能!

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

关于c++ - 为什么我不能在声明中定义静态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64591641/

相关文章:

c++ - 什么是 R 保存终端标志?

C++读取用户输入比较数组

c++ - int *pi = new int(0); 中 int(0) 的含义?

c++ - RTMP FFmpeg 复用示例

c++ - 从线列表中形成面

c++ - std::string 和 placement new

命名空间 std 中的 C++ 互斥锁未命名类型

c++ - 如果整数与指针的大小相同,是否将整数重新解释为指针双射?

c++ - Number Base 转换和数字访问?

c++ - 如何使用静态转换管理共享对象的生命周期?