【问题标题】:how to use a static vector inside a static function如何在静态函数中使用静态向量
【发布时间】: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


    【解决方案1】:

    添加

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

    【讨论】:

      【解决方案2】:

      将此添加到 mainwindow.cpp:

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

      当您在 MainWindow 类中声明 static myVector2 时,这是一种前向声明。您需要在 .cpp 文件之一中创建变量才能使其正常工作。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-07-01
          • 2011-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多