如何访问 c++ 中向量中的子实例
我有一个父类和子类(从父类继承)。 在子类中,我有一个名为 function_blah();
的成员函数,
我使用了 vector
存储 5 个父实例,3 个子实例。因此向量中的元素总数为 8。
我可以轻松访问元素 A[0] 到 A[4] 的成员函数,它们是父实例。 但是每当我尝试访问元素 A[5] 到 A[7] 的成员函数时,编译器都会抱怨类父类没有名为“function_blah”的成员
我访问元素的方式是使用指数。 ex A[i] 其中 i = 0..7。正确吗?如果没有,怎么办?
I have a parent class and child class (inherited from parent).
In the child class, I have a member function named function_blah();
I used vector<parent*> A
to store 5 parent instances, 3 child instances. So the total number of elements in the vector is 8.
I can easily access to member functions of element A[0] to A[4], which are parent instances.
But whenever I try to have access to member functions of element A[5] to A[7], the compiler complains that class parent has no member named 'function_blah'
The way I access to elements is using index. e.x A[i] with i = 0..7. Is it correct? if not, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将指针向下转换为子类才能在其上使用子函数。
当您使用
parent*
访问子对象时,您实际上是在告诉编译器“将此对象视为parent
”。由于 function_blah() 只存在于子进程中,编译器不知道要做什么。您可以通过使用
dynamic_cast
运算符向下转型来改善这一点:这将执行从
parent*
到a的运行时检查、类型安全的强制转换child*
您可以在其中调用function_blah()
。仅当您知道要拉出的对象肯定是
子
而不是父
时,此解决方案才有效。如果存在不确定性,您需要做的是使用继承并在父级上创建一个虚拟方法,然后在子级上重载该方法。You need to downcast the pointer to the child class in order to use child functions on it.
When you're accessing a child object using a
parent*
, you are effectively telling the compiler, "treat this object as aparent
". Sincefunction_blah()
only exists on the child, the compiler doesn't know what to do.You can ameliorate this by downcasting using the
dynamic_cast
operator:This will perform a runtime-checked, type-safe cast from the
parent*
to achild*
where you can callfunction_blah()
.This solution only works if you know that the object you're pulling out is definitely a
child
and not aparent
. If there's uncertainty, what you need to do instead is use inheritance and create a virtual method on the parent which you then overload on the child.您正在存储 Parent*,它没有 function_blah 方法。您需要使 function_blah 成为父级的虚拟方法,或者使用dynamic_cast向下转换为子级*。
You're storing parent*, which has no function_blah method. You need to either make function_blah a virtual method of parent, or use dynamic_cast to downcast to a child*.
成员
_blah()
是否在parent
中声明为虚拟?或者它甚至是在parent
中声明的吗?因为如果没有,那么您将永远无法通过父指针访问_blah()
。是的,您还必须进行向下转型,但前提是您确切地知道您需要的是child
类型。Is member
_blah()
declared virtual inparent
? Or is it even declared inparent
? Because if not, then you'll never be able to access_blah()
through a parent pointer. And yes, you'll also have to downcast, but only if you know exactly that you're expecting achild
type.