-1

我有这个结构:

typedef struct {
    QPolygon polygon;
    QRect position;
} form;

我尝试forms如下初始化,但出现分段错误错误:

int n = 10
forms = (form*) malloc(sizeof(form) * n);
while (n>0) {
   forms[n].position.setRect(0,0,0,0);
   forms[n].polygon=QPolygon(0); //error - segmentation fault
   forms[n].polygon = QPolygon(QRect(x, y, w, h)); //error - segmentation fault
}

我也尝试这样:

QPolygon v;
v = QPolygon(QRect(x, y, w, h)); //ok
v = QPolygon(QRect(x, y, w, h)); //ok
sprites[n].polygon = QPolygon(QRect(x, y, w, h)); //error - segmentation fault

如何将多边形放入结构中?

4

2 回答 2

1

首先,在 C++ 中定义这样的结构:

struct form { // note: Qt naming convention would use upper case first letter
    QPolygon polygon;
    QRect position;
};

在这个答案的最后,有一个更现代的选择,但首先,要直接修复你 20 年的 C++ 风格,像这样编写你的代码(你不应该,但你知道该怎么做):

为此,假设您有

form *forms;

然后你可以让你的代码不会崩溃,如果你这样写:

int n = 10
forms = new form[n]; // bad style in modern C++, use std::vector instead
while (n > 0) {
   --n; // indexes go 9..0
   //forms[n].position.setRect(0,0,0,0); // constructor did this
   //forms[n].polygon=QPolygon(0); // constructor did this
   forms[n].polygon = QPolygon(QRect(x, y, w, h));
}

您的错误可能是,因为结构中的QPolygonQRect实例form未正确构造。很难说,你所做的是未定义的行为,像那样访问未初始化的内存。此外,您n==10在循环的第一次迭代中,超出了有效索引范围 0..9,也可能崩溃了。


此外,当您使用 分配数组时new,您还必须将其作为数组删除,以便正确销毁数组元素:

delete[] forms;

使用现代 C++,您不需要这样做,您可以使用值类型或智能指针。


最后,一个更现代的版本,它更简单、更安全,你不必担心释放内存等问题:

std::vector<form> forms;


int n = 10
forms = std::vector<form>(n); // assign a vector of length n to forms


while (n > 0) {
    ... contents of the loop are same as above ...
}
于 2016-08-30T14:19:53.870 回答
1

由于您正在编写 C++11,而不是 C,因此您的代码应该更简单。利用您正在使用的语言。

emplace_back在向量内构造Form实例:这是最快的方法。您也可以使用push_back,但这会构建一个临时的,不能便宜地移动。

struct Form {
    QPolygon polygon;
    QPoint position; // maybe you meant QRect boundingRect?
    Form(const QPolygon & polygon, const QPoint & position) :
        polygon{polygon}, position{position} {}
    Form() = default;
};

class Class {
    std::vector<Form> forms;
public:
    Class() {
        int x = 0;
        int y = 0;
        int w = 100;
        int h = 100;
        forms.reserve(20); // avoids copies as the vector grows
        for (int i = 0; i < 10; ++i)
            forms.emplace_back(QRect{x,y,w,h}, QPoint{x,y});
        for (int i = 0; i < 10; ++i)
            forms.push_back({QRect{x,y,w,h}, {x,y}}); // uniform initialization
    }
};
于 2016-08-30T14:48:01.593 回答