在boost :: variant中存储类

时间:2016-10-27 12:52:01

标签: c++ boost

有人建议我使用boost :: variant作为形状变量来存储不同类型的形状。但是,当我的代码实现了boost :: variant时,我在编译时遇到了错误。错误说:'Shape':基类未定义且错误更多。

这是我的代码(Object.h):

using Shape = boost::variant<Rectangle, Circle>;

enum Shape_Type
{
    RECTANGLE,
    CIRCLE
};

struct Position
{
    float x, y;

    Position(float position_x, float position_y)
    {
        x = position_x;
        y = position_y;
    }
};

class Object : private Shape
{

private:
    std::string name;

public:
    Object() = default;

    Object(std::string name, Rectangle rectangle) : name(name), Shape(rectangle)
    {
    }

    Object(std::string name, Circle circle) : name(name), Shape(circle)
    {
    }

    void setPosition(float, float);

    void setAngle(float);

    Shape* getShape()
    {
        Shape* shape = this;
        return shape;
    }

    Position getPosition();

    const std::string* getName()
    {
        return &name;
    }
};

class Rectangle
{

private:
    sf::RectangleShape rectangleshape;

public:
    Rectangle() = default;

    Rectangle(float width, float height)
        : rectangleshape(sf::RectangleShape(sf::Vector2f(width, height)))
    {
    }

    void setPosition(float position_x, float position_y)
    {
        rectangleshape.setPosition(position_x, position_y);
    }

    void setAngle(float angle)
    {
        rectangleshape.setRotation(angle);
    }

    sf::RectangleShape* getRectangleShape()
    {
        return &rectangleshape;
    }

    Position getPosition()
    {
        return Position(rectangleshape.getPosition().x,
                        rectangleshape.getPosition().y);
    }
};

class Circle
{

private:
    sf::CircleShape circleshape;

public:
    Circle() = default;

    Circle(std::string name, float radius)
        : circleshape(sf::CircleShape(radius))
    {
    }

    void setPosition(float position_x, float position_y)
    {
        circleshape.setPosition(position_x, position_y);
    }

    void setAngle(float angle)
    {
        circleshape.setRotation(angle);
    }

    sf::CircleShape* getCircleShape()
    {
        return &circleshape;
    }

    Position getPosition()
    {
        return Position(circleshape.getPosition().x,
                        circleshape.getPosition().y);
    }
};

btw是getShape()函数好吗?

1 个答案:

答案 0 :(得分:1)

变量用于静态多态,因此根本不需要基类(动态 - 或虚拟 - 多态)。

变体中的成员通常不共享公共基类,因此您不会拥有getShape函数,或者您需要对其进行模板化:

template <typename T>
T const& getShape() const { return boost::get<T>(_shape); }