简体   繁体   中英

how to use a static vector inside a static function

I am try to use vector<int> myVector2 , however, I have trouble it to use on a static function (foo) . I use Qt and here is the default code below:

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

}

I just added static std::vector<int> myVector2; static void foo(); static std::vector<int> myVector2; static void foo(); to header and void MainWindow::foo(){ MainWindow::myVector2.push_back(3); } void MainWindow::foo(){ MainWindow::myVector2.push_back(3); } on the above code. when I compile it, I get such error:

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'

if I remove static before the vector and function, then it compiles fine but I want these two to be accessible directly.

How is it possible to fix the above code?

Add

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

to mainwindow.cpp.

BTW:

This

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

}

probably should be:

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

}

Add this to mainwindow.cpp:

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

When you declare static myVector2 in MainWindow class, this is kind of forward declararion. You need to create the variable in one of .cpp file to get it working.

您需要定义该向量,并将其放在实现文件(.cpp)中的类声明之外:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM