多态性指向数组的指针 [英] Polymorphism & Pointers to arrays

查看:28
本文介绍了多态性指向数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 A 类:

class A
{
    public:
        virtual double getValue() = 0;
}

还有一个 B 类:

class B : public A
{
    public:
        virtual double getValue() { return 0.0; }
}

然后在 main() 中:

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

如果我这样做:

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.

推荐答案

你不能多态地处理数组,所以 new B[100] 创建一个 B 对象并返回一个指向数组的指针 - 或等效于数组的第一个元素 - 虽然将此指针分配给指向基类的指针是有效的,但将其视为指向数组的指针是无效的A 对象.

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.

这篇关于多态性指向数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆