【发布时间】:2013-11-18 13:59:00
【问题描述】:
我尝试使用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,那么它编译得很好,但我希望这两个可以直接访问。
如何修复上述代码?
【问题讨论】:
标签: c++ qt static-members