【问题标题】:Passing A SImple List Correctly正确传递一个简单的列表
【发布时间】:2015-06-22 20:15:28
【问题描述】:

我是 Qt 和 c++ 的新手。我很难将点列表传递给方法。当我全局声明列表并使用它时,它工作正常,但是当我在本地声明它并将它传递给一个方法时它根本不起作用。(根本不起作用,我的意思是车辆没有要遵循的点列表o它与它在全球范围内声明的情况相反,它什么都不做)

Simulation::Simulation()
{
    QList<QPointF> pointsToFollow3;
    pointsToFollow3  <<QPointF(0,25)<<QPointF(300,25)<<QPointF(1000,25)<<QPointF(1700,25);
    createVehicles(5, pointsToFollow3);
}
void Simulation::createVehicles(int numberOfVehicles, QList<QPointF> pointsToFollow)
{
    spawnVehicle(pointsToFollow);       
}

void Simulation::spawnVehicle(QList<QPointF> pointsToFollow)
{
    //spawn my vehicle
    Vehicle * vehicle = new Vehicle(pointsToFollow);
    vehicle->setPos(pointsToFollow[0]);
    scene->addItem(vehicle);
}

当在头文件中将要遵循的点声明为公共全局变量时,此方法有效,我认为我传递点列表的方式不正确,非常感谢您的帮助。

【问题讨论】:

  • 尝试在Simulation类的构造函数中声明和定义pointsToFollow3
  • 您可以在非工作情况下发布代码吗?很难修复工作代码。
  • 请提供一个完整但最小的例子供读者尝试。
  • 该代码不起作用
  • 我的问题是如何将列表传递给方法?

标签: c++ list qt parameter-passing


【解决方案1】:

真的很难理解你的意思,而且你附上了工作代码,当然不理想,但工作。

在阅读了你的 cmets 之后,我试图实现你想做的事情。

你的头类Simulation:

#include <QObject>

class QGraphicsScene;
class QTimer;
class QPointF;

class Simulation: public QObject
{
    Q_OBJECT
public:
    explicit Simulation(QObject *parent = 0);
    ~Simulation();

private:
    QGraphicsScene *scene;
    QList<QPointF*> *list;
    QTimer *timer;

private slots:
    void spawnVehicle();
};

这是实现:

Simulation::Simulation(QObject *parent) : QObject(parent)
{
    list = new QList<QPointF*>;
    for (int i = 0; i < 10; ++i)
        list->append(new QPointF(i*100, 25));

    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(spawnVehicle()));
    timer->start(1000);
}

在这种方法中,只需写入控制台您的列表元素:

void Simulation::spawnVehicle()
{
    static int currentNumber = 0;

    qDebug() << (*list->at(currentNumber++));

    if (currentNumber >= list->size()) {
        timer->stop();
        deleteLater();
    }
}

在析构函数中你必须释放资源:

Simulation::~Simulation()
{
    delete timer;
    qDeleteAll(list->begin(), list->end());
    list->clear();
    delete list;
    delete scene;    
}

至少我想说,在构造函数中创建 QList&lt;QPointF&gt; 并不是一个好主意;这没有错,但我认为不是正确的OO。

最好的方法是这样做:

使用QList&lt;QPointF&gt; *参数定义Simulation(QList&lt;QPointF&gt; *lst, QObject *parent = 0)构造函数,该构造函数已经创建并填充,并使用该实体进行处理。

希望这个例子对你有用。

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多