c – 返回基类中的抽象类型

在类层次结构的设计中,我使用一个抽象基类来声明派生类将实现的各种方法.从某种意义上讲,基类与C中可以接受的接口相似.但是,有一个具体问题.考虑下面的代码声明我们的接口类:
class Interface {
public:
    virtual Interface method() = 0;
};

class Implementation : public Interface {
public:
    virtual Implementation method() { /* ... */ }
};

当然,这不会编译,因为你不能在C中返回一个抽象类.要解决这个问题,我使用以下解决方案:

template <class T>
class Interface {
public:
    virtual T method() = 0;
};

class Implementation : public Interface<Implementation> {
public:
    virtual Implementation method() { /* ... */ }
};

这个解决方案的工作原理非常好,而且对于我来说,它看起来不是非常优雅,因为文本的冗余位是接口的参数.如果你们能用这个设计指出我们的其他技术问题,我会很开心,但这是我唯一关心的问题.

有没有办法摆脱冗余模板参数?可能使用宏?

注意:所讨论的方法必须返回一个实例.我知道如果method()返回一个指针或引用,那就没有问题.

解决方法

Interface :: method()不能返回一个Interface实例而不使用指针或引用.返回非指针非参考接口实例需要实例化一个Interface本身的实例,因为Interface是抽象的,这是非法的.如果您希望基类返回一个对象实例,则必须使用以下之一:

指针:

class Interface
{
public:
  virtual Interface* method() = 0;
};

class Implementation : public Interface
{
public:
  virtual Interface* method() { /* ... */ }
};

参考:

class Interface
{
public:
  virtual Interface& method() = 0;
};

class Implementation : public Interface
{
public:
  virtual Interface& method() { /* ... */ }
};

模板参数:

template<type T>
class Interface
{
public:
  virtual T method() = 0;
};

class Implementation : public Interface<Implementation>
{
public:
  virtual Implementation method() { /* ... */ }
};

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...