-
October 14th, 2012, 11:09 AM
#1
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
-
October 14th, 2012, 01:47 PM
#2
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.
-
October 14th, 2012, 04:47 PM
#3
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.
-
October 14th, 2012, 05:32 PM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|