Error in C++:Undefined Symbol: Rec::n

Asked

Viewed 25 times

1

Good night to you all!

I’m studying C++, and gave error in the code I tried to compile. I believe it is because the example is a very old book. I’ve tried some kicks, but I haven’t been able to solve the problem yet.

Thanks in advance!

//
//  main.cpp
//  membros_static_1
//
//

#include <iostream>

using namespace std;

class Rec{
private:
    static int n;
public:
    Rec(){n++;}     //Construtor
    int getRec() const{return n;}
};

int main(int argc, const char * argv[]) {
    // insert code here...
    Rec r1, r2, r3;
    
    cout << "\nNumero de objetos: " << r1.getRec();
    cout << "\nNumero de objetos: " << r2.getRec();
    cout << "\nNumero de objetos: " << r3.getRec();
    
    return 0;
}

Thanks in advance for your attention.

2 answers

1

You need to initialize the variable n, but that code: static int n=0; will not work, you need to declare it externally.

First, in case you don’t know, what is a static variable?

A static variable is never allocated to a stack. They have space allocated to different static stores. This means that when we declare a static variable in a class, this variable is shared by all objects in that class.

To declare the static variable, use this code:

tipoDaVariavel Classe::nomeDaVariavel = valorDesejado

Your code would look like this:


#include <iostream>

using namespace std;

class Rec{
private:
    static int n;
public:
    Rec(){n++;}     //Construtor
    int getRec() {return n;}
};

int Rec::n = 0;//declaração da variavel

int main(int argc, const char * argv[]) {
    // insert code here...
    Rec r1, r2, r3;
    
    cout << "\nNumero de objetos: " << r1.getRec();
    cout << "\nNumero de objetos: " << r2.getRec();
    cout << "\nNumero de objetos: " << r3.getRec();
    
    return 0;
}

I also put the code on Repl.it

If you want to take a look at a story that talks about it click here

  • alternative is not to declare n as a statistical variable, then initialize it as int n=0.

  • @Annamaule yes, I could, but with the static da to count how many objects were created :)

0

You didn’t initialize the n, Voce must start with some value, for example int n=0;, otherwise you will have a random memory value ( also known as junk ).

Browser other questions tagged

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