Can a pointer to base point to an array of derived objects?(指向基的指针可以指向派生对象数组吗?)
问题描述
我今天去面试了,被问到这个有趣的问题.
I went to a job interview today and was given this interesting question.
除了内存泄漏和没有虚拟dtor的事实之外,为什么这段代码会崩溃?
Besides the memory leak and the fact there is no virtual dtor, why does this code crash?
#include <iostream>
//besides the obvious mem leak, why does this code crash?
class Shape
{
public:
    virtual void draw() const = 0;
};
class Circle : public Shape
{
public:
    virtual void draw() const { }
    int radius;
};
class Rectangle : public Shape
{
public:
    virtual void draw() const { }
    int height;
    int width;
};
int main()
{
    Shape * shapes = new Rectangle[10];
    for (int i = 0; i < 10; ++i)
        shapes[i].draw();
}
推荐答案
你不能那样索引.您已经分配了一个 Rectangles 数组,并在 shapes 中存储了一个指向第一个的指针.当您执行 shapes[1] 时,您正在取消引用 (shapes + 1).这不会为您提供指向下一个 Rectangle 的指针,而是指向假定的 Shape 数组中的下一个 Shape 的指针.当然,这是未定义的行为.在你的情况下,你很幸运并且撞车了.
You cannot index like that. You have allocated an array of Rectangles and stored a pointer to the first in shapes. When you do shapes[1] you're dereferencing (shapes + 1). This will not give you a pointer to the next Rectangle, but a pointer to what would be the next Shape in a presumed array of Shape. Of course, this is undefined behaviour. In your case, you're being lucky and getting a crash.
使用指向 Rectangle 的指针可以使索引正常工作.
Using a pointer to Rectangle makes the indexing work correctly.
int main()
{
   Rectangle * shapes = new Rectangle[10];
   for (int i = 0; i < 10; ++i) shapes[i].draw();
}
如果你想在数组中有不同种类的 Shape 并多态地使用它们,你需要一个 指针 到 Shape 的数组.
If you want to have different kinds of Shapes in the array and use them polymorphically you need an array of pointers to Shape.
这篇关于指向基的指针可以指向派生对象数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:指向基的指针可以指向派生对象数组吗?
				
        
 
            
        基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				