可以通过引用以基类作为参数的函数来传递派生类 [英] Is it possible to pass derived classes by reference to a function taking base class as a parameter

查看:307
本文介绍了可以通过引用以基类作为参数的函数来传递派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个抽象基类 IBase 和纯虚拟方法(一个接口)。

Say we have an abstract base class IBase with pure virtual methods (an interface).

从基类中派生 CFoo CFoo2

我们有一个知道如何使用IBase的函数。

And we have a function that knows how to work with IBase.

Foo(IBase *input);

在这些情况下,通常的情况是这样的:

The usual scenario in these cases is like this:

IBase *ptr = static_cast<IBase*>(new CFoo("abc"));
Foo(ptr);
delete ptr;

但是指针管理最好避免,所以在这种情况下有没有办法使用引用?

But pointer management is better to be avoided, so is there a way to use references in such scenario?

CFoo inst("abc");
Foo(inst);

其中 Foo 是:

Foo(IBase &input);


推荐答案


你不必上传你的对象。

Yes. You don't have to upcast your objects. All references/pointers to derived types are converted implicitly to base objects references/pointers when necessary.

所有:

IBase* ptr = new CFoo("abc"); // good
CFoo* ptr2 = static_cast<CFoo*>(ptr); // good
CFoo* ptr3 = ptr; // compile error

CFoo instance("abc");
IBase& ref = instance; // good
CFoo& ref2 = static_cast<CFoo&>(ref); // good
CFoo& ref3 = ref; // compile error



当您必须下载时,您可能需要考虑使用 dynamic_cast ,如果你的类型是多态的。

When you have to downcast you may want to consider using dynamic_cast, if your types are polymorphic.

这篇关于可以通过引用以基类作为参数的函数来传递派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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