簡體   English   中英

隊列會發生什么? (c++)

[英]What happens to a queue? (c++)

        queue1.h        mainwindow.h
        /               /
        A.h---Mainwindow.cpp

A #includes queue1 Mainwidow #includes AA 和 MainWindow 都需要使用 queue1 的一個實例,所以我在 A 中將其定義為“static queue1 q1;” 然后在啊,我在 q1 中按“A”,但是當我嘗試 output 它在主窗口中時,我得到了垃圾。 當我嘗試在 mainwindow.h 中推送“主窗口”,然后是 output 就可以了。 我正在使用 Qt 4.7.0 並贏得 7。

隊列1.h

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

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

#endif // QUEUE1_H

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

#endif // A_H

如果你取消注釋 "q1.q.push("mainwindow");" 該程序將首先 output "mainwondow" 然后垃圾箱。 在該隊列變為空之后。

主窗口.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.front().c_str());
    q1.q.pop();


}

對於這個測試項目,我沒有更改 mainwindow.h,但它就在這里。

主窗口.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並不意味着它在這種情況下的意思 - 它從符號中刪除了外部鏈接,這意味着它只能在給定的翻譯單元中可見。 因為你在 header 中有它,由兩個單元包含,所以你的 class 會有兩個不同的實例——所以當你推入 A 時,你推入 A 中的隊列,而不是主窗口中的隊列。

解決方案是將變量聲明為extern ,並僅在一個翻譯單元中定義它。

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

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

現在 A 和 mainwindow 都將使用相同的隊列(當然您需要從 Ah 中刪除static queue1 q1; )。

將 q1 聲明為外部,而不是 static。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM