Help with static members
Hi, I was making a pogram to demostrate static variables and I don't know why my compiler (VS 2005) is giving me these crazy errors that my book im using said I shouldn't be getting. Here is my program, please help:
header:
class number{
private:
static int num;
public:
int getnum()
{return num;}
void setnum(int innum)
{num=innum;}
};
body (.cpp)
#include<iostream>
#include"headerr.h"
using namespace std;
int main()
{
int innum=0;
class number test;
test.setnum(10);
cout<<test.getnum();
system("pause");
return (0);
}
This code returns the errors:
body.obj : error LNK2019: unresolved external symbol "private: static int number::num" (?num@number@@0HA) referenced in function "public: static int __cdecl number::getnum(void)" (?getnum@number@@SAHXZ)
1>C:\Documents and Settings\Computer stuff man\Desktop\test progams\classes 3.0\Debug\classes 3.0.exe : fatal error LNK1120: 1 unresolved externals
CPPRULZ
Junior Poster in Training
91 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
You need to define num as well as declare it:
class number{
private:
static int num;
public:
int getnum()
{return num;}
void setnum(int innum)
{num=innum;}
};
int number::num;
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Does it matter where you do this (int number::num) because I tried it out in the main and it works now but why? It doesn't seem to do anything other than maybe introduce it into a new block however you put it in the header and it still works. So what does it really do ?
CPPRULZ
Junior Poster in Training
91 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
My real question now is why do I need the syntax number::num; - what does it do physically in the program.
CPPRULZ
Junior Poster in Training
91 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
So, just to check, int number::num; clears a place to store data at a certain data location-just like when you declare a class variable you give all of the variables in the class a place in physical memory and an adress however the adress holds NULL.
CPPRULZ
Junior Poster in Training
91 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
Line 2 of your second code snippet : #include"headerr.h"
Two rr's?
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661