如何在不重载纯虚函数的情况下将抽象类转换为普通类? [英] how to convert abstract class to normal class without overload pure virtual function?

查看:26
本文介绍了如何在不重载纯虚函数的情况下将抽象类转换为普通类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的代码:

class A
{
public:
    virtual int getN() = 0;
};

class B : public A
{
private:
    int n = 2;
public:
    int getN() { return n; }
};
class C : public A
{
    // do not contain property n, it nolonger need getN();
};

A 类是抽象类.现在我有从 A 派生的 C 类.但它不像 B 类有一个属性 n.所以我不能重载getN(),然后类C是一个抽象类,我不能实例化它.那么如果我想实例化C类,我该怎么做?

class A is a abstract class. Now I have class C derived from A. But it dose not like class B has a property n. So I can't overload getN(), and then class C is a abstract class, which I cannot instantiate it. So if I want instantiate class C, what should I do?

推荐答案

继承代表一种种类"关系.

Inheritance represents a "kind-of" relationship.

由于 C 没有 getN() 方法,所以它不能是一种"A,因为任何持有对A 有权期望 getN() 出现.

Since C does not have a getN() method, it cannot be a "kind of" A since anyone holding a reference to an A has the right to expect getN() to be present.

他们有这个权利,因为你通过将 getN 放在 A 的公共虚拟接口中来断言它.

They have this right because you asserted it by putting getN in the public virtual interface of A.

故事的寓意——尽可能避免继承.首选封装.

Moral of the story - avoid inheritance if you can. Prefer encapsulation.

这篇关于如何在不重载纯虚函数的情况下将抽象类转换为普通类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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