加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:58:56 所属栏目:百科 来源:网络整理
导读:在类层次结构的设计中,我使用一个抽象基类来声明派生类将实现的各种方法.从某种意义上讲,基类与C中可以接受的接口相似.但是,有一个具体问题.考虑下面的代码声明我们的接口类: class Interface {public: virtual Interface method() = 0;};class Implementat
在类层次结构的设计中,我使用一个抽象基类来声明派生类将实现的各种方法.从某种意义上讲,基类与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() { /* ... */ }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读