在子类中将非纯虚函数转换为纯虚函数 [英] Turning a non-pure virtual function into pure in a subclass

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

问题描述

所以,我有这个多态层次结构:

ClassA不是抽象的,没有纯虚函数,而是几个虚函数B类:公共A类为某种类型的子类定义扩展接口;是抽象的,带有纯虚函数C类:公共B类可用的类,不再需要子类化

这是交易,我将把 ClassAClassC 的对象一起扔到容器中并进行迭代.为了执行这个迭代,一个非纯虚函数存在于 ClassA 中,但只有 {} 是空的;也就是说,它是空的,只有在迭代遇到 ClassC 时才可用,在这种情况下它被调用,否则它什么都不做.我不能让它是纯的,否则我不能拥有 ClassA 的对象.

但是为了确保ClassC确实实现了那个函数,迫使那个类的用户这样做,我在ClassB中把这个函数设为纯虚函数.>

这可以接受吗?如果我采用非纯虚函数,将其设为纯,然后在 ClassC 中再次设为非纯,则什么都不会破坏"?

解决方案

如果按照您在解释中提出的方式实施,您就可以了.无需深入了解抽象基类和虚函数的整个部分,标准规定:

<块引用>

C++ § 10.4p2

抽象类是只能作为其他类的基类使用的类;不能创建抽象类的对象,除非作为从它派生的类的子对象.如果一个类至少有一个纯虚函数,那么它就是抽象的.[注意:这样的函数可能会被继承:见下文.— end note ] 通过在类定义的函数声明中使用纯说明符 (9.2) 来指定虚函数是纯的.纯虚函数只需要在使用限定 ID 语法 (5.1) 或如同使用 (12.4) 调用时才需要定义

上面引用的下面"导致此注释:

<块引用>

C++11 § 10.4p5

[注意:抽象类可以从非抽象类派生,纯虚函数可以覆盖非纯虚函数.- 尾注]

So, I have this polymorphic hierarchy:

ClassA
Is not abstract, no pure virtual functions, but a few virtual functions

ClassB:public ClassA
Defines an extended interface for a certain type of subclass; 
 is abstract with pure virtual functions

ClassC:public ClassB
Usable class, no more subclassing

Here's the deal, I will have objects of ClassA and ClassC thrown together into containers and iterated through. To perform this iteration, a non-pure virtual function is present in ClassA but is empty with just {}; that is, it is empty, made available only if the iteration encounters a ClassC in which case it is invoked, otherwise it does nothing. I can't have it be pure otherwise I cannot have objects of ClassA.

But to ensure that ClassC does in fact implement that function, forcing the user of that class to do so, I make this function pure virtual in ClassB.

Is this acceptable? Nothing will "break" if I take a non-pure virtual function, make it pure, then make it non-pure again in ClassC ?

解决方案

You're fine if implemented as you present in your explanation. Without going into entire sections on abstract base classes and virtual functions, the standard dictates:

C++ § 10.4p2

An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function. [ Note: Such a function might be inherited: see below. — end note ] A virtual function is specified pure by using a pure-specifier (9.2) in the function declaration in the class definition. A pure virtual function need be defined only if called with, or as if with (12.4), the qualified-id syntax (5.1)

The "below" referenced above leads to this note:

C++11 § 10.4p5

[Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. - end note]

这篇关于在子类中将非纯虚函数转换为纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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