0

Say I have a static member defined in header file like:

static QHash<QString,int> flagColorsMap;

How can I define the hashmap inside the constructor that is in the cpp file. If I do the following:

Classname::flagColorsMap.insert("xyz",22);

it gives compile error :: undefined reference to Classname::flagColorMap.

Sumeet
  • 8,086
  • 3
  • 25
  • 45
  • 2
    Have you initialized `flagColorsMap` ? – pSoLT Jan 19 '17 at 11:19
  • 1
    That's a linker error. Try adding a `QHash Classname::flagColorsMap` to define the static member, in one and only one source file that has visibility of (e.g. includes) the class definition. – Peter Jan 19 '17 at 11:39
  • Why are you using class qualificator? – Rama Jan 19 '17 at 12:08
  • Then you somehow misinterpreted or mis-applied my advice. The substance of the answer you subsequently accepted (after it was edited due to you also saying it was "not working") is the same advice, and the edit was simply an example. – Peter Jan 20 '17 at 07:52
  • @Peter I completely agree with you. I retract my previous statement. – Sumeet Jan 20 '17 at 07:53

2 Answers2

2

In .cpp file put this line:

QHash<QString,int> Classname::flagColorsMap;

Edited: Please check this really simple example of static QHash member initialization: create new Qt Quick project and edit MainWindow class:

// 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 = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    static QHash<QString,int> flagColorsMap;

};

#endif // MAINWINDOW_H

And source file:

// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

QHash<QString,int> MainWindow::flagColorsMap;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    MainWindow::flagColorsMap.insert("xyz",22);

}

MainWindow::~MainWindow()
{
    qDebug() << "Value=" << flagColorsMap.value("xyz");
    delete ui;
}

Is it still does not work?

trivelt
  • 1,913
  • 3
  • 22
  • 44
0

I think you got this compile error because you are just "delcare" flagColorsMap but not "define" it. So define flagColorsMap in the .cpp file maybe this error will disappeared.

GodBird
  • 31
  • 1
  • 4