【问题标题】:Error C3892: You cannot assign to a variable that is const错误 C3892:您不能分配给 const 变量
【发布时间】:2015-11-04 16:09:49
【问题描述】:

我正在用 C++ 制作游戏。我还没有开始编写游戏,我正在设置不同的类并制作菜单。这是我第一次制作“大”程序,我发现自己将所有内容都设置为静态。当我将类中的所有内容设为静态时,出于某种原因,我需要将变量设为 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

这是我的 GameWindow 类:

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 整数的值 - 但我不知道如何解决。

【问题讨论】:

  • const = 常量 = 不可变 = 无法更改。顺便说一句,每个 GameWindow 实例不应该有自己的宽度和高度吗?
  • 你为什么要让所有这些成员static
  • 为什么要在 GameWindow 类中管理屏幕上的信息?你不应该有一个单例 Screen 类吗?
  • @i4h 正如我所说,这是我的第一个大型程序,所以请原谅我做错了一切。你需要从某个地方开始,对吧?我修复了错误,但现在我有 9 个“未解决的外部符号”错误。它们与库或文件有关,我找不到修复它的方法。
  • @bames53 我需要你的帮助 ^

标签: c++ constants sfml


【解决方案1】:

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

在头文件中:

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

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

在源文件中:

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

【讨论】:

    【解决方案2】:

    当我将类中的所有内容设为静态时,出于某种原因,我需要将变量设为 const。

    不,你没有。如果您希望它们是静态的非常量,则需要在 .cpp 文件中定义它们。

    或者更好的是,首先使它们成为非静态的。所有GameWindows 共享相同的宽度和高度以及相同的RenderWindow 是没有意义的。

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

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

    【讨论】:

      【解决方案3】:

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

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

      如果您希望能够更改它,请删除const(连同类声明中的赋值),并使用该语句在一个编译单元中定义变量

      int GameWindow::ScreenWidth = 1024;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 2016-11-10
        • 2021-11-01
        • 2011-01-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多