在虚拟函数中使用子类类型参数 [英] Using subclass type parameters in virtual functions

查看:114
本文介绍了在虚拟函数中使用子类类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码(是我在现实生活中的麻烦)

I have this piece of code (contrived from my real-life trouble)

它无法编译,抱怨ExtendsB没有实现B::Run(A* a).但是,理解A* Run();

It cannot compile, complaining ExtendsB does not implement B::Run(A* a). However, it has no problems understanding the extension to A* Run();

class A { };

class ExtendsA : public A { };

class B
{
public:
    virtual ~B(){}  
    virtual void Run(A* a) = 0;
    virtual A* Run() = 0;
};

class ExtendsB : public B
{
public:
    virtual ~ExtendsB(){}

    // Not OK! It does not see it as an implementation of 
    // virtual void Run(A* a) = 0;
    virtual void Run(ExtendsA* ea) {}; 
    virtual ExtendsA* Run() { return new ExtendsA(); }; // OK
};

为什么C ++允许将返回类型更改为子类,但不允许将参数类型更改为子类?

这是一个很好的基本原理还是只是语言规范中的一个遗漏点?

Is it a good rationale or just a missed point in the language specifications?

推荐答案

为什么C ++允许将返回类型更改为子类,但不允许将参数类型更改为子类?

C ++标准允许您使用 协变量返回类型 ,但它覆盖了虚函数,但不允许您修改函数参数.是的,它背后有一个很好的理由.

C++ standard allows you to use a Covariant return type while overidding virtual functions but does not allow you to modify the function parameters.And yes there is a good rationale behind it.

理论价格:

从本质上讲,重写意味着在运行时将根据指针所指向的实际对象调用基类方法或派生类方法.
它意味着:
即:在不更改调用代码的情况下,可以调用Base类方法的每个实例都可以替换为对Derived类方法的调用."

Overriding essentially means that either the Base class method or the Derived class method will be called at run-time depending on the actual object pointed by the pointer.
It implies that:
i.e: "Every instance where the Base class method can be called can be replaced by call to Derived class method without any change to calling code."

如果没有上述规则,它将通过添加新功能(新派生类)留下一个打破现有代码的窗口.

If the above rule was not in place it would leave a window to break the existing code by addition of new functionality(new derived classes).

如果派生类中的函数原型与基类虚拟函数的w.r.t参数不同,则该函数不会覆盖基类函数,因为上述规则已被破坏.

If you have a function prototype in derived class which differs from base class virtual function w.r.t parameters then the function does not override the base class function, since the above rule gets broken.

但是,协变量返回类型不会违反此规则,因为向上隐式发生,并且基类指针始终可以指向派生类对象而无需任何强制转换,因此标准对返回类型强制采用了协变量返回类型的这种条件.

However, Covariant return types do not break this rule, because upcasting happens implicitly and a Base class pointer can always point to a derived class object without any casting, hence the Standard enforces this condition of covariant return types on return types.

这篇关于在虚拟函数中使用子类类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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