有没有办法upcast到一个抽象类,而不是修改它每次一个类派生自它? [英] Is there no way to upcast into an abstract class and not modify it each time a class is derived from it?

查看:111
本文介绍了有没有办法upcast到一个抽象类,而不是修改它每次一个类派生自它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;

class Abs
{
        public:
        virtual void hi()=0;
};

class B:public Abs
{
        public:
        void hi() {cout<<"B Hi"<<endl;}
        void bye() {cout<<"B Bye"<<endl;}
};
class C:public Abs
{
        public:
        void hi() {cout<<"C Hi"<<endl;}
        void sayonara() {cout<<"C Sayonara"<<endl;}
};

int main()
{
        Abs *bb=new B;
        bb->bye();
        Abs *cc=new C;
        cc->sayonara();
}//main

编译器说

test2.cpp: In function ‘int main()’:
test2.cpp:26: error: ‘class Abs’ has no member named ‘bye’
test2.cpp:28: error: ‘class Abs’ has no member named ‘sayonara’

因为这个问题,我每次创建一个新的派生类继承时,我必须添加功能Abs类(向上转换是强制的我要做的我计划要求它是如此)。我不想触摸基类创建后。
不是这个问题违反了原则,一旦你做一个基类,你不必修改它。任何方式来解决这个问题?
ps:我已经看到了工厂设计模式和原型设计模式,但是他们似乎都无法解决它。

Because of this problem, I'll have to add functions to the Abs class each time I create a new derived class which inherits from it (Upcasting is compulsory for me to do. The program I'm planning requires it to be so). I don't want to touch the base class once it's created. Doesn't this problem violate the principle that once you make a base class, you won't have to modify it ever. Any way to resolve this problem? p.s: I've seen the factory design pattern and the prototype design patterns, but both of them can't seem to be able to solve it.

推荐答案

好吧,我不知道你想要什么(以及为什么你想要这样),但:

Well, i'm not sure to understand exactly what you want (and why you want it that way) but:

int main()
{
        Abs *bb=new B;
        static_cast<B*>(bb)->bye();
        Abs *cc=new C;
        static_cast<C*>(cc)->sayonara();
}//main

将工作。

你只需要确保 bb 在你之前真的是 B * c> static_cast 。

You just have to be sure that bb is really a B* before you static_cast.

您也可以使用 dynamic_cast 如果 bb 的类型不正确。

You may also use dynamic_cast which will return a null pointer if bb is not of the correct type.

这篇关于有没有办法upcast到一个抽象类,而不是修改它每次一个类派生自它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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