我正在尝试将矩形转换为多边形,但是当我尝试运行转换函数时,我得到了废话。
这是我的代码:
#include <iostream>
struct Polygon {
int nPoints;
int* xPoints;
int* yPoints;
Polygon(int nPoints, int* xPoints, int* yPoints) :
nPoints(nPoints), xPoints(xPoints), yPoints(yPoints) {
}
};
struct Shape {
virtual Polygon toPolygon() = 0;
};
struct Rectangle : public Shape {
int x;
int y;
int width;
int height;
Rectangle(int x, int y, int width, int height) :
x(x), y(y), width(width), height(height) {
}
virtual Polygon toPolygon() {
int xPoints[] = {x, x + width, x + width, x};
int yPoints[] = {y, y, y + height, y + height};
return Polygon(4, xPoints, yPoints);
}
};
int main (int argc, char** argv) {
Rectangle rect = Rectangle(14, 8, 45, 64);
Polygon polygon = rect.toPolygon();
for (int i = 0; i < polygon.nPoints; i++) {
std::cout << polygon.xPoints[i] << ", " << polygon.yPoints[i] << std::endl;
}
}
这是输出:
14, 8
32588, 32588
6299872, -383502305
0, 32588
输出的点与我定义的矩形点完全不同,如果有人能告诉我原因,我会很感激。
(如果有人想知道为什么Shape结构存在,那是因为我计划在让这个系统使用矩形后添加更多形状。)
答案 0 :(得分:1)
xPoints和yPoints在toPolygon方法中声明。一旦方法返回,它们就会超出范围。用于创建多边形的指针则变为未定义。