【问题标题】:C++/CLR - overload method inside interface classC++/CLR - 接口类中的重载方法
【发布时间】:2018-04-30 14:52:51
【问题描述】:

有没有办法将接口方法的许多签名分配给一个实现?

例如,任何ITransformable 都可以通过矢量或三倍坐标移动:

public interface class ITransformable
{
public:
    void move(double x, double y, double z);
    void move(Vector ^ offset);
};

这种表示法要求程序员在每个子类中实现这两种方法,但其中只有一个具有有用的主体,其他的只会引用第一个类似

public ref class Thing : public ITransformable
{
    virtual void move(double x, double y, double z)
    {
        //Each child implements it in it's own way
        ...
    }
    virtual void move(Vector ^ offset)
    {
        //It is the same for all childs, copy it and paste everywhere
        move(offset->x, offset->y, offset->z);
    }
}

有没有类似的东西:

public interface class ITransformable
{
public:
    //Implement me
    void move(double x, double y, double z);

    //Need no overriding anymore, just use implementation of the method above
    void move(Vector ^ offset) : move(offset->x, offset->y, offset->z);
};

没有多重继承(假设Thing继承了一些非接口类,所以ITransformable不能是抽象类)。

【问题讨论】:

  • 这是不可能的,只有抽象基类可以做到这一点。实现接口的类中的单行方法不会让你慢很多。

标签: inheritance interface c++-cli overloading clr


【解决方案1】:

没有办法做你正在寻找的东西。接口是纯粹的,从不包含任何实现。

您可以认为这两种方法是多余的,只提供一种就足够了。

如果两个重载都采用一个参数,并且可以转换参数,那么您最接近您正在寻找的内容。比如定义方法取VectorFloat,用VectorInt调用会调用转换。

【讨论】:

  • 正如你所说,没有答案,所以我不会接受它,但要投赞成票
猜你喜欢
  • 2022-01-23
  • 2015-10-31
  • 2011-06-15
  • 2013-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
相关资源
最近更新 更多