我正在尝试做一些非常简单的事情,无法弄清楚为什么我会收到此错误:
mainwindow.obj:-1: error: LNK2001: unresolved external symbol "public: static class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > const MazeBuilder::algorithms" (?algorithms@MazeBuilder@@2V?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@B)
我想使用枚举访问一个字符串向量,所以我有一种很好的方法来写出要抓取的内容,其他所有类都可以使用它。
这是我的代码的简化版:
MainWindow.cpp
#include "MainWindow.h"
#include "MazeBuilder.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow (QWidget* parent) : QMainWindow (parent), ui (new Ui::MainWindow)
{
ui->setupUi (this);
//Add available algorithms to the combo box
for (size_t i = 0; i < MazeBuilder::algorithms.size(); i++)
{
ui->algorithmBox->addItem(MazeBuilder::algorithms.at(i).c_str());
}
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
private:
Ui::MainWindow* ui;
};
#endif // MAINWINDOW_H
MazeBuilder.cpp
#include "MazeBuilder.h"
//Binds to MazeBuilder::MazeAlgorithm
//const static std::vector<std::string> algorithms = {"Prim's"};
const std::vector<std::string> MazeBuilder::algorithms = {"Prim's"};
MazeBuilder::MazeBuilder()
{
}
MazeBuilder.h
#ifndef MAZEBUILDER_H
#define MAZEBUILDER_H
#include <string>
#include <vector>
class MazeBuilder
{
public:
enum MazeAlgorithm
{
PRIM = 0
};
const static std::vector<std::string> algorithms;
MazeBuilder();
};
#endif // MAZEBUILDER_H
整个项目(小型)在这里:https://mega.nz/#!ruoRCZbQ!Jk79ATSO0POb9J_xkaAeNIy9ycVTnHkp1iT4Vq5XFoM
答案 0 :(得分:3)
您遇到范围问题。由于algorithms
被声明为MazeBuilder
的静态成员,因此也需要这样定义。将其在MazeBuilder.cpp中的定义更改为
const std::vector<std::string> MazeBuilder::algorithms = {"Prim's"};
否则,您只是在全局范围内定义静态变量algorithms
。
下面的最小代码编译和链接对我来说都很好
#include <iostream>
#include <string>
#include <vector>
class MazeBuilder {
public:
const static std::vector<std::string> algorithms;
MazeBuilder();
};
const std::vector<std::string> MazeBuilder::algorithms = {"Prim's"};
MazeBuilder::MazeBuilder() {
}
int main(int argc, char** argv) {
for(std::string s : MazeBuilder::algorithms) {
std::cout << s << std::endl;
}
return 0;
}