使用基类对象访问派生的仅类方法 [英] Accessing derived class-only methods using base class object

查看:83
本文介绍了使用基类对象访问派生的仅类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OO编程的新手,我想知道如何解决以下问题-

I am new to OO programming and I was wondering how to solve the following question -

我有以下内容:

class A
{
    public:
    A() {};
    ~A() {};

    virtual functionA() = 0;
}

class B: public A
{
    public:
    B() {};
    ~B() {};

    functionA();
    functionB();
}

是否有使用基类A的对象访问functionB的方法?如果没有,为什么不可能呢?如果是,请问该如何做?我试图在此站点上找到此答案,但没有找到任何具体答案.

Is there a way to access functionB using an object of the base class A? If no, why is it not possible? If yes, how does one do it? I tried to find this answer on this site but I didn't find anything concrete.

推荐答案

我将对您的示例进行一些修改,以使您更好地理解:

I would modify your example slightly to give you a better understanding:

class Animal
{
    public:
    A() {};
    ~A() {};

    virtual Eat() = 0;
}

class Bird: public Animal
{
    public:
    B() {};
    ~B() {};

    Eat();
    Fly();
}

是否应该允许Animal对象访问属于Bird的函数Fly? 不,因为不是全部 AnimalBird. 但是,如果您确定某个特定的Animal对象不是Bird,则可以将Animal对象下放到Bird,然后调用Fly函数.
但是,通常不建议这样做.向上广播(将Bird广播到Animal)是可以的,因为所有Bird都是Animal s.

Should an Animal object be allowed to access the function Fly which belongs to Bird ?
No, because not all Animals are Birds. But if you are sure than a specific Animal object is a Bird, then you can downcast the Animal object to Bird and then call Fly function.
However, this is not generally recommended. Upcasts (casting Bird to Animal) are okay because all Birds are Animals.

这篇关于使用基类对象访问派生的仅类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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