开发者

What happens to a queue? (c++)

开发者 https://www.devze.com 2023-03-08 19:08 出处:网络
queue1.hmainwindow.h // A.h---Mainwindow.cpp A #includes queue1 Mainwidow #includes A A and MainWindow both need to use one instanse of queue1, so i define it in A like \"static queue1 q1;\"
        queue1.h        mainwindow.h
        /               /
        A.h---Mainwindow.cpp

A #includes queue1 Mainwidow #includes A A and MainWindow both need to use one instanse of queue1, so i define it in A like "static queue1 q1;" Then in A.h i push "A" in a q1, but when i try to output it in mainwindow i get trash. When i try to push "mainwindow" inside mainwindow.h and then output it is ok. I'm using Qt 4.7.0 and win 7.

queue1.h

#ifndef QUEUE1_H
#define QUEUE1_H
#include <queue>
#include <string>

class queue1
{
public:
    queue1();
   std::queue<std::string> q;
};

#endif // QUEUE1_H

A.h

#ifndef A_H
#define A_H
#include "queue1.h"
static queue1 q1;
class A
{
public:
    A(){q1.q.push("A");}
};

#endif // A_H

If you uncomment "q1.q.push("mainwindow");" the program will first output "mainwondow" and then trash. After that queue become empty.

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "a.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //q1.q.push("mainwindow");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    ui->label->setText(q1.q.开发者_C百科front().c_str());
    q1.q.pop();


}

For this test project i didn't changed mainwindow.h but here it is.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

private slots:
    void on_pushButton_clicked();
};

#endif // MAINWINDOW_H


static does not mean what you mean it does in this context — it takes away external linkage from a symbol, meaning it will only be visible within a given translation unit. And because you have it in the header, included by two units, there will be two distinct instances of your class — so when you push in A, you push to the queue in A, not the queue in mainwindow.

The solution is to declare the variable as extern, and define it in only one translation unit.

// in queue1.h
class queue1 { ... };
extern queue1 q1;

// in e.g. queue1.cpp
#include "queue1.h"
queue1 q1;

Now both A and mainwindow will use the same queue (of course you need to remove static queue1 q1; from A.h).


Declare q1 as extern, not static.

0

精彩评论

暂无评论...
验证码 换一张
取 消