派生类的抽象基类,这些派生类的函数具有派生类的返回类型 [英] Abstract base class for derived classes with functions that have a return type of the derived class

查看:175
本文介绍了派生类的抽象基类,这些派生类的函数具有派生类的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对从基类派生的所有类强制使用某个API。通常,您使用具有纯虚函数的抽象基类来执行此操作。但是,如何处理返回派生类型的函数?

I would like to force a certain API for all classes derived from the base class. Normally, you do that using an abstract base class that has purely virtual functions. However, how do you handle functions that return the derived type? How do I go about forcing that type of function?

struct base
{
    virtual base func() = 0;
};

struct deriv1 : base
{
    deriv1 func();
};

struct deriv2 : base
{
    deriv2 func();
};

此示例将给出诸如成员函数的无效抽象返回类型之类的错误。我已经看到了一些建议返回指针的答案,但是我并不特别想为此而陷入动态内存,并且跟踪所有分配的指针将是一种特殊的情况。有想法吗?

This example will give an error like "invalid abstract return type for member function". I've seen some answers that suggest returning pointers, but I don't particularly want to dip into dynamic memory for that and keeping track of all the allocated pointers would be a special kind of hell. Any ideas?

推荐答案

当虚拟函数返回指向类的指针或引用时,该类将从基类继承并覆盖该函数,允许将返回类型更改为指针或对从原始返回类型派生的类的引用。

When a virtual function returns a pointer or reference to a class, a class which inherits from the base class and overrides the function is allowed to change the return type to a pointer or reference to a class which is derived from the original return type.

您不能按值返回基数因为它是抽象的,所以您实际上不能自己创建一个。

You can't return base by value as it is abstract so you can't actually create one by itself.

http://zh.wikipedia.org/wiki/Covariant_return_type

使用虚函数和基类时,通常必须使用动态分配以创建对象。我建议您研究智能指针以帮助管理内存。

When using virtual functions and base classes, you usually have to use dynamic allocation to create your objects. I suggest you look into smart pointers to help manage the memory.

这篇关于派生类的抽象基类,这些派生类的函数具有派生类的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆