错误 C3892:您不能分配给 const 变量

Error C3892: You cannot assign to a variable that is const

我正在用 C++ 制作游戏。我还没有开始编写游戏代码,我正在设置不同的 classes 并制作菜单。这是我第一次制作 "big" 程序,我发现自己将所有内容都设为静态。当我将 classes 中的所有内容设为静态时,我出于某种原因需要将变量设为 const

error C2864: 'GameWindow::ScreenHeight': a static data member with an in-class initializer must have non-volatile const integral type 

当我将它们设为 const 时,出现另一个错误:

error C3892: 'ScreenHeight': you cannot assign to a variable that is const

这是我的游戏窗口class:

class GameWindow {
public:
    static sf::RenderWindow mainWindow;

    static void SetScreenWidth(int x);
    static int GetScreenWidth();
    static void SetScreenHeight(int x);
    static int GetScreenHeight();

    static void Initialize();

private:
    static const int ScreenWidth = 1024;
    static const int ScreenHeight = 576;
};

出于某种原因我不能这样做

void GameWindow::SetScreenHeight(int x) {
    ScreenHeight = x;
}

我知道是什么导致了问题 - 我无法更改 const 整数的值 - 但我不知道如何解决它。

When I make everything in my classes static I for some reason need to make the variables const.

不,你不知道。如果您希望它们是静态的,则需要在 .cpp 文件中定义它们 and non-const.

或者更好的是,首先让它们成为非静态的。所有 GameWindow 共享相同的宽度和高度,以及相同的 RenderWindow.

是没有意义的

另外,Initialize方法是怎么回事? class 的 构造函数 应该进行初始化。

是时候重新考虑您的设计了。避免static,避免public成员变量,避免非构造函数初始化方法。 特别是如果这是一个大项目。

在写 static const int ScreenWidth = 1024; 时,您是在告诉编译器 ScreenWidth 无法更改。 (然后编译器可以进行各种优化 - 可能会完全从代码中消除常量)。

因此尝试更改它会发出编译器警告。

如果您希望能够更改它,请删除 const(连同 class 声明中的赋值),然后 define使用语句

在恰好一个编译单元中的变量

int GameWindow::ScreenWidth = 1024;

只需声明 class 定义中的变量并在外部定义它们:

在头文件中:

class GameWindow {
    /* Whatever here... */

    private:
    static int ScreenWidth;
    static int ScreenHeight;
};

并且在源文件中:

int GameWindow::ScreenWidth = 1024;
int GameWindow::ScreenHeight = 576;