C++ 是否可以通过引用以基类为参数的函数来传递派生类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9285627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to pass derived classes by reference to a function taking base class as a parameter
提问by Coder
Say we have an abstract base class IBase
with pure virtual methods (an interface).
假设我们有一个IBase
带有纯虚方法(一个接口)的抽象基类。
Then we derive CFoo
, CFoo2
from the base class.
然后我们从基类派生CFoo
, CFoo2
。
And we have a function that knows how to work with IBase.
我们有一个知道如何使用 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);
where Foo
is:
在哪里Foo
:
Foo(IBase &input);
回答by gwiazdorrr
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.
是的。您不必向上转换您的对象。必要时,所有对派生类型的引用/指针都会隐式转换为基对象引用/指针。
So:
所以:
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
When you have to downcast you may want to consider using dynamic_cast
, if your types are polymorphic.
当您不得不向下转型时dynamic_cast
,如果您的类型是多态的,您可能需要考虑使用。
回答by John
You can cast an object just as you can a pointer. I remember this was common when converting char
to unsigned char
and various other sign changing casts in days of yore.
您可以像转换指针一样转换对象。我记得在过去的日子里,这在转换char
为unsigned char
和其他各种符号转换时很常见。