c++ - 在 vector 容器中使用的对象中具有 const 变量

标签 c++

所以我正在尝试制作蛇克隆。

我创建了一个 BodyPiece 类,其中包含某些我希望为常量的变量,因为它们不应更改。当我只是创建一个 Bodypiece 实例进行测试时,这不是问题。但是我希望能够随着蛇的生长添加碎片,所以我制作了一个 vector 体变量。从下面的代码可以看出:

在 BodyPiece.h 中:

#pragma once
#include "D3DGraphics.h"
#include "Keyboard.h"
#include "Direction.h"

class BodyPiece
{
public:
    BodyPiece(int xPos, int yPos, Direction* dir);
    ~BodyPiece();
    void Draw(D3DGraphics& gfx);
    void UpdateDirection(KeyboardClient& kbd);
    void Move();
private:
    Direction* dir;
    int xPos;
    int yPos;
    int width = 5;
    int height = 5;
    int vx = 5;
    int vy = 5;
};

在Game.h文件中

声明的 BodyPiece vector 体:

std::vector<BodyPiece> body;

在Game.cpp文件中

vector 在初始化列表中初始化。

body({ {400, 300, &d } })

如果我在 BodyPiece 中设置任何变量为常量,它将产生一个错误:

error C2582 'operator=' 函数在类 BodyPiece 中不可用。

我的问题是:

是什么原因造成的?我在网上看了,有一点点想法,但真的只有一点点。

我怎样才能拥有 const 变量,使用 vector 容器(或其他类型的容器,如果有帮助,不必是 vector )并让编译器满意?还是我应该完全改变我的方法?

提前谢谢你。

最佳答案

问题是,如果您没有赋值运算符,那么编译器会为您生成一个,对成员进行简单的浅拷贝。但是,如果您有实际的 const 成员变量(而且不仅像您的那样默认初始化),那么这些变量将无法复制,编译器也无法创建赋值运算符。

简单的解决方案是使常量成为实际常量和static,这样它们就是的成员,而不是单个对象的一部分:

class BodyPiece
{
    ...
    static int const width = 5;
    static int const height = 5;
};

这样做的唯一缺点是您需要在单个源文件中实际定义这些成员变量:

int const BodyPiece::width;
int const BodyPiece::height;

另一种解决方案是显式创建一个赋值运算符来复制所需的数据:

class BodyPiece
{
public:
    ...
    BodyPiece& operator=(BodyPiece const& other)
    {
        // Copy data from other to this
        xPos = other.xPos;
        ...
        return *this;
    }
    ...
};

关于c++ - 在 vector 容器中使用的对象中具有 const 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36742422/

相关文章:

C++ 简单的字符串替换,不复杂的代码,但会产生疯狂的错误

C++ 模板头 cpp 分离,将 *.cpp 包含到 *.h 中的解决方案不再有效

c++ - 收集不同类型的类并在 C++ 中调用它们的方法

c++ - 绑定(bind)后编译器抛出错误 "expected initializer before int"一直在尝试学习 c++,我只是一直卡住

c++ - std::stable_partition() 和 std::partition() 有什么区别?

c++ - 短路模板实例化

c++ - 实现安全左移

c++ - 返回类型与返回类型 (operator++) 不相同也不协变

c++ - 计算 opencv 二值图像中的 'white' 个像素(高效)

C++ 模板 : Hint template arguments to compiler?