gpt4 book ai didi

c++ - 在此代码中调用赋值运算符的位置在哪里?

转载 作者:行者123 更新时间:2023-11-27 23:27:16 26 4
gpt4 key购买 nike

我被告知我必须为我的 Bullet 类定义一个赋值运算符,但我的印象是,您真正需要实现三规则的唯一时间是您自己显式处理内存时,例如指针类成员(member)。

我实际上被告知试图调用 operator= 的行是 std::vector<Bullet> bullets在下面的代码中。我只是不明白赋值运算符在哪里被调用,为什么被调用。我无处做类似 Bullet bullet1 = bullet2 的事情;

编辑 - 还有,为什么默认赋值运算符不合适?我在 Bullet 的层次结构中的任何地方都没有指针成员。

感谢您的帮助。

#ifndef GUN_H
#define GUN_H

#include "gameObject.h"
#include "Bullet.h"
#include <vector>

class Mesh;

class Gun : public GameObject
{
private:
std::vector<Bullet> bullets; // this line right here

protected:
virtual void TriggerPulled() = 0;

public:
Gun(Mesh& mesh);

virtual ~Gun();

std::vector<Bullet>& Bullets();
};

#endif

这是同一文件的来源:

#include "Gun.h"
#include "Mesh.h"

Gun::Gun(Mesh& mesh) : GameObject(mesh)
{
bullets = std::vector<Bullet>();
}

Gun::~Gun() {}

std::vector<Bullet>& Gun::Bullets()
{
return bullets;
}

这是子弹:

#ifndef BULLET_H
#define BULLET_H

#include "BoundingSphere.h"
#include "helperMethods.h"
#include "GameObject.h"

class Bullet : public GameObject
{
private:
float velocity;
float distance;
D3DXVECTOR3 firedFrom;
BoundingSphere bSphere;

public:
Bullet(D3DXVECTOR3 position, D3DXVECTOR3 rotation, float velocity, D3DXCOLOR colour, Mesh& mesh);
~Bullet();

BoundingSphere& BulletSphere();
};

#endif

包围球:

#ifndef BOUNDING_SPHERE_H
#define BOUNDING_SPHERE_H

#include <d3d10.h>
#include <d3dx10.h>

class Ray;
class BoundingBox;

class BoundingSphere
{
private:
D3DXVECTOR3 centre;
float radius;
public:
BoundingSphere(D3DXVECTOR3 position, float radius);
BoundingSphere();
bool Intersects(BoundingSphere boundingSphere);
bool Intersects(BoundingBox boundingBox);
bool Intersects(Ray ray, D3DXVECTOR3& result);

// getters
const D3DXVECTOR3 Centre();
const float Radius();

// setters
void BoundingSphere::Centre(D3DXVECTOR3 centre);
};

#endif

游戏对象:

#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H

#include <d3d10.h>
#include <d3dx10.h>

class Mesh;

class GameObject
{
private:
D3DXVECTOR3 scale;
D3DXVECTOR3 rotation;
D3DXVECTOR3 position;
D3DXCOLOR colour;

D3DXMATRIX matFinal;

Mesh& mesh;

protected:
void Draw(D3DMATRIX matView, D3DMATRIX matProjection);

public:
GameObject(Mesh& mesh);
virtual ~GameObject();

//getters
const D3DXVECTOR3 Scale();
const D3DXVECTOR3 Rotation();
const D3DXVECTOR3 Position();
const D3DXCOLOR Colour();

//setters
void Scale(D3DXVECTOR3 scale);
void Rotation(D3DXVECTOR3 rotation);
void Position(D3DXVECTOR3 position);
void Colour(D3DXCOLOR colour);
};

#endif

最佳答案

GameObject(及其所有衍生品)包含对 Mesh 的引用。引用在构造时初始化,不能重新赋值,因此在这种情况下编译器不会生成默认赋值运算符。

关于c++ - 在此代码中调用赋值运算符的位置在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448644/

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