C++ - Implementation of class Statica cpp

Asked

Viewed 58 times

1

Hello! I was trying to implement a Static class but had the following error: "Undefined Reference to matematica::Cod" but the variable Cod is in . h follows the code below class . h and cpp;

#ifndef MATEMATICA_H
#define MATEMATICA_H


class matematica
{
  public:
    static int getCod();
    static void setCod(int);

  protected:

  private:
    static int cod;

};

#endif // MATEMATICA_H 

CPP CLASS:

#include "matematica.h"


void matematica::setCod(int c)
{
   matematica::cod = c;
}

I don’t know what to do.

  • 1

    And why would I do this?

  • I’m learning to play with Static class. to know a little bit about its implementation. but I have no idea why this error is happening

  • 1

    The point is that almost always a static class is an error in C++. In the presented form it seems to be totally a mistake, because it seems that it should be a normal class. If you try to make a static class where you should be a normal one, you’ll be learning wrong. So you don’t even have the concept of static class in C++, you can have static members, but not the whole class, and if everyone is static you have a great chance you don’t need a class.

  • 1

    Can Mineiro give an example of how to use correctly? I always had doubts

  • Not for two reasons, it is not our goal of Sopt to give examples, to answer open questions where any answer can be right or wrong. But mostly because I would never use a "static" class, either one is wrong for me. Static class is an interesting concept in languages like Java or C#.

1 answer

1


In the header file you are just declaring the static variable. In other words you are just giving a name and a type. The variable is not "created". Somewhere else (for example, in the corresponding .cpp file) you need to define the variable, that is, effectively create it.

Just think: if the variable were not a static variable it would also not exist until an instance of the class was created.

DRT;

In the corresponding . cpp file do:

int matematica::cod = 0;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.