开发者

object type private class members

开发者 https://www.devze.com 2023-04-12 14:28 出处:网络
Both bounding box and cube take a few arguments in their constructor Header: #ifndef WALL_H #define WALL_H

Both bounding box and cube take a few arguments in their constructor

Header:

#ifndef WALL_H
#define WALL_H

#include "cube.h"
#include "BoundingBox.h"

class Wall
{
    private:
        Cube* cube;
        BoundingBox* boundingBox;
    public:
        Wall(D3DXVECTOR3 min, D3DXVECTOR3 max);
        ~Wall();
        void Draw(D3DXMATRIX matView, D3DXMATRIX matProjection);
};

#endif

Source:

#include "Wall.h"

Wall::Wall(D3DXVECTOR3 min, D3DXVECTOR3 max)
{
    cube = new Cube(D3DXCOLOR(255, 20, 20, 255), min, max);
    boundingBox = new BoundingBox(min, max);
}

void Wall::Draw(D3DXMATRIX matView, D3DXMATRIX 开发者_JS百科matProjection)
{
    cube->Draw(matView, matProjection);
}

Wall::~Wall()
{
    delete cube;
    delete boundingBox;
}

My question is, how would I modify these classes so that cube and boundingBox are not pointers but simply instances? thanks in advance.


Quite simple. Just like this:

#ifndef WALL_H
#define WALL_H

#include "cube.h"
#include "BoundingBox.h"

class Wall
{
private:
Cube cube;
BoundingBox boundingBox;
public:
Wall(D3DXVECTOR3 min, D3DXVECTOR3 max);
void Draw(D3DXMATRIX matView, D3DXMATRIX matProjection);
};

#endif

source:

#include "Wall.h"

Wall::Wall(D3DXVECTOR3 min, D3DXVECTOR3 max)
    :cube(D3DXCOLOR(255, 20, 20, 255), min, max)
    ,boundingBox(min, max)
{
}

void Wall::Draw(D3DXMATRIX matView, D3DXMATRIX matProjection)
{
    cube.Draw(matView, matProjection);
}


Make cube and boundingBox regular (non-pointer) class members, then use an initializer list to call the appropriate constructor for them, e.g.

Wall::Wall(D3DXVECTOR3 min, D3DXVECTOR3 max) :
  cube(D3DXCOLOR(255, 20, 20, 255), min, max),
  boundingBox(min, max)
{
   // nothing
}


First of all, this is wrong when you work with pointers: boundingBox = BoundingBox(min, max); there should be a new before the BoundingBox.

You could simply adjust the declaration of the attributes inside the class:

class Wall
{
private:
    Cube cube;
    BoundingBox boundingBox;
public:
    Wall(D3DXVECTOR3 min, D3DXVECTOR3 max);
    ~Wall();
    void Draw(D3DXMATRIX matView, D3DXMATRIX matProjection);
};

Now you adjust your CTOR:

Wall::Wall(D3DXVECTOR3 min, D3DXVECTOR3 max) : cube(D3DXCOLOR(255, 20, 20, 255), min, max), boundingBox(min, max)
{ }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号