Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Qt使用循环声明成员名称_C++_Qt_Qgraphicsitem_Declare - Fatal编程技术网

C++ Qt使用循环声明成员名称

C++ Qt使用循环声明成员名称,c++,qt,qgraphicsitem,declare,C++,Qt,Qgraphicsitem,Declare,我需要在Qt中处理512个单独的矩形项,我正在qgraphicscene中实现这些项。我真的不想手动声明所有512个元素,除非我真的必须这样做。目前,我有如下想法: QGraphicsRectItem *rec1; QGraphicsRectItem *rec2; QGraphicsRectItem *rec3; QGraphicsRectItem *rec4; QGraphicsRectItem *rec5; QGraphicsRectItem *rec6; QGraphicsRectItem

我需要在Qt中处理512个单独的矩形项,我正在qgraphicscene中实现这些项。我真的不想手动声明所有512个元素,除非我真的必须这样做。目前,我有如下想法:

QGraphicsRectItem *rec1;
QGraphicsRectItem *rec2;
QGraphicsRectItem *rec3;
QGraphicsRectItem *rec4;
QGraphicsRectItem *rec5;
QGraphicsRectItem *rec6;
QGraphicsRectItem *rec7;
QGraphicsRectItem *rec8;
QGraphicsRectItem *rec9;
QGraphicsRectItem *rec10;
QGraphicsRectItem *rec11;
QGraphicsRectItem *rec12;
等等。这必须上升到rec512

我已尝试实现一个for循环来为我实现这一点:

   for(int i = 1;i=512;i++){
        QGraphicsRectItem *rec[i];
    }
然而,我得到一个错误,说“预期的成员名称或;声明说明符之后

我认为在这里实现循环是不可能的,有没有其他方法可以轻松声明所有512项


谢谢:)

感谢Benjamin Lindley指出数组的明显用途,这让我完全忘记了

    QGraphicsRectItem *rec[512];
更好的方法:

// in some .cpp file
#include <QVector>
#include <QSharedPointer>
#include <QDebug>

// Suppose we have some Test class with constructor, destructor and some methods
class Test
{
public:
    Test()
    {
        qDebug() << "Creation";
    }

    ~Test()
    {
        qDebug() << "Destruction";
    }

    void doStuff()
    {
        qDebug() << "Do stuff";
    }
};

void example()
{
    // create container with 4 empty shared poiters to Test objects
    QVector< QSharedPointer<Test> > items(4);

    // create shared poiters to Test objects
    for ( int i = 0; i < items.size(); ++i )
    {
        items[i] = QSharedPointer<Test>(new Test());
    }

    // do some stuff with objects
    for ( int i = 0; i < items.size(); ++i )
    {
        items.at(i)->doStuff();
    }

    // all Test objects will be automatically removed here (thanks to QSharedPointer)
}
//在某些.cpp文件中
#包括
#包括
#包括
//假设我们有一些带有构造函数、析构函数和一些方法的测试类
课堂测试
{
公众:
测试()
{

qDebug()你已经开始使用像Qt这样的高级框架了,你甚至还没有学会数组?我真不敢相信我竟然没有想到这一点。我全神贯注地学习QGraphics的东西,使用数组初始化完全忘记了。谢谢你,我建议你研究一下,或者在Qt环境中哪个更容易处理。什么时候在罗马。。。。