Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call a static method in Qt

Tags:

c++

class

static

qt

I have a simple class containing a static attribute. There are two static methods in this class: one to get the static attribute and the other to initialize it. Yet when call the static method the compiler reports an error.

The class:

class Sudoku {
    Cell Grid[9][9];
    int CurrentLine;
    int CurrentColumn;

    void deleteValInColumn(int val, int col);
    void deleteValInRow(int val, int row);
    void deleteValInBox(int val, int x, int y);
    static int unsetted; //!
public:
    static void IniUnsetted() { //!
        unsetted = 0;
    }
    static int GetUns() { //!
        return unsetted;
    }
    Sudoku(ini InitGrid[9][9]);
    void Calculate_Prob_Values();
    Cell getCell(int x, int y);
    QVector<int> getPossibleValues(int x, int y);
    bool SolveIt();
};

This is the error I get:

In member function 'bool Sudoku::SolveIt()':
no return statement in function returning non-void [-Wreturn-type]
In function `ZN6Sudoku6GetUnsEv':
undefined reference to `Sudoku::unsetted` error: ld returned 1 exit status
like image 874
Oussaki Avatar asked Dec 18 '13 13:12

Oussaki


2 Answers

You will need to define the static variable, even if it is not initialized explicitly. That is what is missing in your code. You should have provided a simple example to reproduce the issue, but for your convenience I am providing one which works.

main.cpp

class Foo {
    public:
        static int si;
        static void bar();
};

int Foo::si = 0; // By default, it will be initialized to zero though.

void Foo::bar() {
     Foo::si = 10;
};

int main()
{
    Foo::bar();
    return 0;
}

Note: I would suggest to get someone to review your code because "unsetted" is incorrect English. If we are at it, you would probably need to fix your indentation as well.

like image 188
lpapp Avatar answered Sep 27 '22 21:09

lpapp


In your code there is no definition of unsetted, there is only declaration.

The solution is to put somewhere in your cpp file a line like this:

int Sudoku::unsetted

The reason for that is that each instantiation of Sudoku class will use the same unsetted member so it cannot be defined for each of them, so it's up to programmer to define it in one place only.

like image 41
Michał Walenciak Avatar answered Sep 27 '22 21:09

Michał Walenciak