Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

static data members in a class.....

Status
Not open for further replies.

epx

Programmer
Feb 18, 2002
3
US
Ok, I have 3 static data members defined for a class "calculator" in a file ('calculator.h') how do initialize these for use?
The three data memberes are:
static float display
static float num1
static char command

i have tried putting them in the constructor like this:

float calculator::display = 0;
float calculator::num1 = 0;
char calculator::command = ' ';

it gives me these errors:

E:\School\CPS271\mp2\calculator.cpp(15) : error C2655: 'display' : definition or redeclaration illegal in current scope
E:\School\CPS271\mp2\calculator.cpp(15) : error C2655: 'num1' : definition or redeclaration illegal in current scope
E:\School\CPS271\mp2\calculator.cpp(15) : error C2655: 'command' : definition or redeclaration illegal in current scope

When I take off scope resolution it gives me these errors:

calculator.obj : error LNK2001: unresolved external symbol "private: static float calculator::display" (?display@calculator@@0MA)
calculator.obj : error LNK2001: unresolved external symbol "private: static float calculator::num1" (?num1@calculator@@0MA)
calculator.obj : error LNK2001: unresolved external symbol "private: static char calculator::command" (?command@calculator@@0DA)

Anyone have a clue??

Thanks again!
 
Static member initialization occurs in class scope. Therefore, they can access other member data or functions.

class SomeClass
{
private:
static int m_someValue;
};

// in your cpp file
int SomeClass::m_someValue = 1;
 
I did that...look at the message above. It just doesn't work for some reason.
 
You must initialize them out of Functions (for example, at begin of calculator.cpp file as follow):
float calculator::display = 0;
float calculator::num1 = 0;
char calculator::command = ' ';

calculator:: calculator()
{
}
 
It works for another classes so as shown by 'epx' and me.
Without Your code I can ask some Questions only.
May be Your header is included twice? Do You use #ifndef/#endif in *.h - Files to avoid it?
Or have You or Microsoft or another Firm declared class 'calculator' in another Files? Or parent - class have such variables?
And why all Errors are on the Line 15? Are all definitions in the same line?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top