0

Please, I don't know why this simple code is rejected.

It give me 2 compilation errors. Help me please.

I use Code::Blocks 20.03

My compiler is GNU GCC

---move.hpp---

class Move {
    public:
        Move();
        Move(int, int);  
    public:
        int from;
        int to;
    
        const static Move NONE = Move(0,-1); //error here
        //undefined reference if I use 
        //const static Move NONE;
};

---move.cpp---

#include "move.hpp"
Move::Move() {
    this->from = 0;
    this->to = 0;
}
Move::Move(int from, int to) {
    this->from = from;
    this->to = to;
}

---main.cpp---

#include <iostream>
#include "move.hpp"

int main(){
    Move move = Move::NONE;//error here
    std::cout << move.from << std::endl;
    std::cout << move.to << std::endl;
    return 0;
}
le Mandarin
  • 192
  • 10
  • Have a look at this question: https://stackoverflow.com/questions/1563897/static-constant-string-class-member . Either declare the static member inline or define it in the source file instead of the header. You should include the errors you get in your question. – Peter H Jul 08 '22 at 10:55

2 Answers2

0

I've found a solution of my problem. In fact, we can't create an object class reference in class definition because the size of this class is unknown.

why can't we declare object of a class inside the same class?

I ve created a namespace (all name in lower case) for do the work.

namespace move {
    const static Move NONE;
}
le Mandarin
  • 192
  • 10
0

You should provide an out-of-class definition for the static data member NONE in the source file(like move.cpp) which will work because at that point the class is complete as shown below:

move.hpp

#pragma once 
class Move {
    public:
        Move();
        Move(int, int);  
    public:
        int from;
        int to;
        //declaration for NONE
        const static Move NONE    ;
//------------------------------^^------>no in class initializer here
        
};

move.cpp

#include "move.hpp"
//definition for Move::NONE
const Move Move::NONE = Move(0,-1);

Move::Move() {
    this->from = 0;
    this->to = 0;
}
Move::Move(int from, int to) {
    this->from = from;
    this->to = to;
}

Working demo

Jason
  • 36,170
  • 5
  • 26
  • 60