c++ - 如何在静态函数中使用静态 vector

标签 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;

};

.....

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/

相关文章:

C++如何访问派生类中的基类静态成员?

c++ - 使用 BOOST 测试异常

c++ - 为什么在 std::vector 上删除提升迭代器

qt - 如何在Qt中创建一个具有完整路径的新文件?

caching - 在不是结构方法的函数上实现缓存的惯用方法是什么?

c++ - 在类嵌套静态 const 成员变量初始化 Clang vs GCC 哪个编译器是正确的?

c++ - 平面平铺成不规则大小的矩形

c++ - Mac OS X 应用程序的编程语言

python - 获取当前在 Windows 或 Ubuntu 上运行的程序列表

qt - QListWidget 根据内容调整大小