多态性与指向数组的指针
问题描述
I have a class A:
And a class B:
And then in main() I do:
If instead I do:
Everything compiles fine, but it seems as though there is something wrong with my polymorphism perhaps? I'm puzzled.
You can't treat arrays polymorphically, so while new B[100]
creates an array of B
objects and returns a pointer to the array - or equivalently the first element of the array - and while it is valid to assign this pointer to a pointer to a base class, it is not valid to treat this as a pointer into an array of A
objects.
The principal reason that you can't is that (typically) derived objects are a different size to their base classes, so attempting to access the array as an array of base class objects will not use the correct offset to get a pointer to the next base class subobject of the next member of the derived class array.
这篇关于多态性与指向数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!