我正在尝试使用 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();
标题和 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
在 vector 和函数之前,然后它编译得很好,但我希望这两个可以直接访问。
如何修复上面的代码?
最佳答案
添加
std::vector<int> MainWindow::myVector2;
到 mainwindow.cpp。
顺便说一句:
这个
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;
}
关于c++ - 如何在静态函数中使用静态 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20049614/