CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2012
    Posts
    11

    Static data of a class

    Hello, I'm new to the forum and would like some help. I am studying the use of static data into classes and the code below is returning an error ...

    ------------------------------------------------------------------------------------------------
    #include <iostream>
    using namespace std;

    class REC
    {
    private:
    static int n; //Dado que será único na classe e alterado por todos os objetos
    public:
    REC() {n++;} // Construtor
    int getrec() const {return n;}
    };

    void main()
    {
    REC r1,r2,r3;
    cout << "\nO numero de objetos de R1: " << r1.getrec();
    cout << "\nO numero de objetos de R2: " << r2.getrec();
    cout << "\nO numero de objetos de R3: " << r3.getrec();
    }
    ------------------------------------------------------------------------------------

    The error:
    main.obj:-1: error: LNK2001: unresolved external symbol "private: static int REC::n" (?n@REC@@0HA)
    Note: I'm using QT Creator

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Static data of a class

    static variables must be defines as well as declared:

    Code:
    class REC
     {
     private:
    
     static int n; //Dado que será único na classe e alterado por todos os objetos
     public:
    
        REC() {n++;} // Construtor
        int getrec() const {return n;}
     };
    
    int REC::n;  // define

    Also, it should be int main, not void main.

  3. #3
    Join Date
    Oct 2012
    Posts
    11

    Re: Static data of a class

    Excuse my ignorance, but I could not understand his explanation. You can fix mei code so I can see what is wrong? I will be very grateful.

  4. #4
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Static data of a class

    1) I did fix your code ... see the line that I added in my first post:

    Code:
    int REC::n;  // define
    2) google: defining static member variables c++

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured