Polymorphism amp; Pointers to arrays(多态性与指向数组的指针)
问题描述
I have a class A:
class A
{
public:
virtual double getValue() = 0;
}
And a class B:
class B : public A
{
public:
virtual double getValue() { return 0.0; }
}
And then in main() I do:
A * var;
var = new B[100];
std::cout << var[0].getValue(); //This works fine
std::cout << var[1].getValue(); //This, or any other index besides 0, causes the program to quit
If instead I do:
B * var;
var = new B[100];
std::cout << var[0].getValue(); //This works fine
std::cout << var[1].getValue(); //Everything else works fine too
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.
这篇关于多态性与指向数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多态性与指向数组的指针
基础教程推荐
- C++ #define 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++按值调用 1970-01-01
- C语言访问数组元素 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- 初始化变量和赋值运算符 1970-01-01
- C++定义类对象 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23