我被告知我必須爲我的Bullet類定義一個賦值操作符,但是我的印象是,只有當你真正需要實現三條規則時,纔會自己明確地處理內存,比如指針類成員。在這個代碼中調用賦值操作符在哪裏?
我被告知,試圖調用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
BoundingSphere所:
#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
並且你知道爲什麼默認賦值運算符不適合我的課嗎? – SirYakalot
@SirYakalot:是的,我編輯了答案......這是因爲參考成員。 –
所以它可能會寫一個重載的運算符=在GameObject中,甚至沒有子彈那麼高,對吧?因爲Bullet的默認操作符=會在GameObject中調用正確的重載?或者是那個錯誤...? – SirYakalot