gpt4 book ai didi

c++ - 在 C++ 中修改静态成员变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:09 45 4
gpt4 key购买 nike

我正在尝试定义一个带有静态成员变量 MAX_DIST 的类 Util,在以下意义上,

class Util{

public:
static double MAX_DIST;
Util():MAX_DIST(400.0){}
};

并能够在其他类中更新它,例如

Util::MAX_DIST = 387.98;

这给了我一个错误:

‘double Util::MAX_DIST’ is a static data member; it can only be initialized at its definition

但是,如果我在其定义处初始化 MAX_DIST,例如

class Util{

public:
static const double MAX_DIST = 400;
Util();
};

(我必须按照编译器的指示添加“const”,否则我会收到“ISO C++ 禁止非 const 静态成员的类内初始化”错误)现在我不能在其他地方修改 MAX_DIST,因为它现在只准备好了:

error: assignment of read-only variable ‘Util::MAX_DIST’

在网上搜索无果后,我找不到解决这个悖论的方法。有人可以帮帮我吗?

最佳答案

将其放入您的 Util.cpp(或任何文件名)文件中:

double Util::MAX_DIST = 0;

静态变量需要初始化。

长答案,引用标准 9.4.2 $2:

The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class (3.3.7).

关于c++ - 在 C++ 中修改静态成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13442909/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com