对象类型私有类成员

时间:2011-10-13 12:30:44

标签: c++

边界框和多维数据集在其构造函数中都有一些参数

部首:

#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

来源:

#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 matProjection)
{
    cube->Draw(matView, matProjection);
}

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

我的问题是,如何修改这些类,以便cube和boundingBox不是指针而只是实例?提前谢谢。

3 个答案:

答案 0 :(得分:2)

非常简单。就像这样:

#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

源:

#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);
}

答案 1 :(得分:0)

生成cubeboundingBox常规(非指针)类成员,然后使用初始化列表为它们调用适当的构造函数,例如

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

答案 2 :(得分:0)

首先,当您使用指针时,这是错误的:boundingBox = BoundingBox(min, max); new之前应该有BoundingBox

您可以简单地调整类中属性的声明:

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

现在你调整你的CTOR:

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