有没有办法向上转换为抽象类并且每次从它派生类时都不修改它? [英] Is there no way to upcast into an abstract class and not modify it each time a class is derived from it?

查看:24
本文介绍了有没有办法向上转换为抽象类并且每次从它派生类时都不修改它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 类添加函数(Upcasting 对我来说是强制性的.我计划的程序要求它是所以).一旦创建基类,我就不想碰它.这个问题是不是违反了一个原则,一旦你创建了一个基类,你就不必再修改它了.有什么办法可以解决这个问题?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

会起作用.

在你static_cast之前,你只需要确定bb真的是一个B*.

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.

这篇关于有没有办法向上转换为抽象类并且每次从它派生类时都不修改它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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