如何创建使用扩展它的类的接口

时间:2018-04-04 03:19:12

标签: c++-cli

我正在编写一些假设的练习代码,我遇到了一个设计问题。

假设我有一个GameObject类:

public ref class GameObject : GameObjectBluePrint {
public:
    property double health;
    property double damage;
    property double defense;
    property double strideLength;
    property System::Drawing::Point location;

public:
    virtual void Attack(GameObject% enemy) {
        enemy.health -= this->damage;
    }
    virtual void Defend(GameObject% enemy) {
        this->health -= enemy.damage * 0.5;
    }
    virtual void Move(Direction direction) {
        switch (direction) {
        case Direction::up:
            this->location.Y += this->strideLength;
            break;
        case Direction::down:
            this->location.Y -= this->strideLength;;
            break;
        case Direction::right:
            this->location.X += this->strideLength;;
            break;
        case Direction::left:
            this->location.X -= this->strideLength;
            break;
        }
    }
    virtual bool isVisible(GameObject% otherObject) {
        double distance = Math::Sqrt(Math::Pow(this->location.X - otherObject.location.X, 2) + Math::Pow(this->location.Y - otherObject.location.Y, 2));
        return distance <= 2;
    }
};

我想制作不同类型的这些对象,所以我创建了一个这个类扩展的接口:

public interface class GameObjectBluePrint {
    void Attack(GameObject% enemy);
    void Defend(GameObject% enemy);
    void Move(Direction direction);
    bool isVisible(GameObject% otherObject);
};

问题是此接口依赖于首先定义的GameObject类。但是,对于要定义的GameObject类,我必须扩展此接口。我是否错误地使用了这个界面概念,或者有没有办法避免像这样的嵌套混乱?

1 个答案:

答案 0 :(得分:0)

如何合并https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern https://msdn.microsoft.com/de-de/library/2kb28261.aspx

generic <typename TGameObject>  
public interface class class GameObjectBluePrint {
    void Attack(TGameObject% enemy);
    void Defend(TGameObject% enemy);
    void Move(Direction direction);
    bool isVisible(TGameObject% otherObject);
};

public ref class GameObject : GameObjectBluePrint<GameObject> {
...
}