问题描述
我写了一个抽象类(使用 虚函数),我想有一个方法接受一个这样的类作为参数。鉴于类是抽象的,我理解我不能将一个抽象类传递给任何方法,但为什么不能将一个抽象类的子类传递给该方法?如何指定参数应该是指定基类的任何子类?
I've written an abstract class (with pure virtual functions), and I'd like to have a method accept one such class as a parameter. Given that the class is abstract, I understand that I couldn't pass an abstract class to any method, but why can't I pass a subclass of an abstract class to that method? How do I specify that a parameter should be any of the subclasses of a specified baseclass? This is all in C++.
推荐答案
您需要将参数指定为指针(或引用),例如。 Abstract *
而不是 Abstract
。如果 Derived
继承自 Abstract
,则可以传递 Derived *
当抽象*
是预期的,但是你不能通过传递类型 Derived
code>需要抽象。
You need to specify the parameter as a pointer (or reference), e.g. Abstract *
rather than Abstract
. If Derived
inherits from Abstract
, you can pass a variable of type Derived *
when Abstract *
is expected, but you can't in general pass one of type Derived
when Abstract
is expected.
这篇关于传递抽象参数到方法,为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!