저는 오늘 면접을 보러 갔고이 흥미로운 질문을 받았습니다.
메모리 누수와 가상 dtor가 없다는 사실 외에도이 코드가 충돌하는 이유는 무엇입니까?
#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();
}
Shape **직사각형의 배열을 가리키고 있어야합니다 . 그런 다음 액세스는 shapes [i]-> draw ();
->편집자에 의해 실수였다.