如何在静态函数中使用静态向量

Joh*_*der 0 c++ qt static-members

我正在尝试使用vector<int> myVector2,但是,在static function (foo). 我使用 Qt,下面是默认代码:

   Mainwindow.h
---------------------------------------------------
#include <QMainWindow>
#include <vector>
#include <iostream>
#include <QString>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    static std::vector<int> myVector2;
    static void foo();
private:
    Ui::MainWindow *ui;

};
Run Code Online (Sandbox Code Playgroud)

……

mainwindow.cpp
------------------------------
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foo;

}

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

void MainWindow::foo(){
    MainWindow::myVector2.push_back(3);

}
Run Code Online (Sandbox Code Playgroud)

我刚刚添加static std::vector<int> myVector2; static void foo();到标题和 void MainWindow::foo(){ MainWindow::myVector2.push_back(3); }上面的代码中。当我编译它时,我收到这样的错误:

mainwindow.o: In function `MainWindow::foo()':
mainwindow.cpp:(.text+0xe7): undefined reference to `MainWindow::myVector2'
mainwindow.cpp:(.text+0xee): undefined reference to `MainWindow::myVector2'
mainwindow.cpp:(.text+0x10e): undefined reference to `MainWindow::myVector2'
mainwindow.cpp:(.text+0x126): undefined reference to `MainWindow::myVector2'
collect2: error: ld returned 1 exit status
make: *** [ddd] Error 1
14:46:36: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project ddd (kit: Desktop)
When executing step 'Make'
Run Code Online (Sandbox Code Playgroud)

static如果我在向量和函数之前删除,那么它可以正常编译,但我希望这两个可以直接访问。

如何修复上述代码?

Tom*_*mek 5

添加

std::vector<int> MainWindow::myVector2;
Run Code Online (Sandbox Code Playgroud)

到mainwindow.cpp。

顺便提一句:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foo;

}
Run Code Online (Sandbox Code Playgroud)

可能应该是:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foo(); // <- note () here;

}
Run Code Online (Sandbox Code Playgroud)