问题描述
我是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
?不,因为不是全部 Animal
是Bird
.但是,如果您确定某个特定的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 Animal
s are Bird
s. 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 Bird
s are Animal
s.
这篇关于使用基类对象访问派生的仅类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!