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

问题描述

我有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.

推荐答案

您不能把阵列多态,所以当新型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.

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

09-02 10:46