簡體   English   中英

如何在靜態函數中使用靜態向量

[英]how to use a static vector inside a static function

我嘗試使用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;

};

.....

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);

}

我剛剛添加了static std::vector<int> myVector2; static void foo(); static std::vector<int> myVector2; static void foo(); 到標題並void MainWindow::foo(){ MainWindow::myVector2.push_back(3); } 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'

如果我在向量和函數之前刪除static ,則可以正常編譯,但我希望直接訪問這兩個函數。

如何解決以上代碼?

std::vector<int> MainWindow::myVector2;

到mainwindow.cpp。

BTW:

這個

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

}

可能應該是:

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

}

將此添加到mainwindow.cpp中:

std::vector<int> MainWindow::myVector2;

MainWindow類中聲明static myVector2 myVector2時,這是一種前向聲明。 您需要在.cpp文件之一中創建變量才能使其正常工作。

您需要定義該向量,並將其放在實現文件(.cpp)中的類聲明之外:

std::vector<int> MainWindow::myVector2;

暫無
暫無

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

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