
Originally Posted by
yyiu002
with line : int A::myID = 0;
When I put it inside header file where class A was defiined, I get error like: multiple definition of `A::myID', why is that? I am sure there are "#ifndef A_H
#define A_H " to stop class A was included more than once.
You got to learn about c++ way of doing this things, so you create a header file (a.h) for the class definition (here you don't write the implementation of the functions, just the definition) and you write a second file (a.cpp) that include the a.h and here you write the implementation (it's not like in c#) and don't forget about the include guards (they are not useless)
Example:
//a.h file
#ifndef A_H
#define A_H
class A{
static int myID;
int member;
public:
A();
A(A&); //copy c-tor
int id(); // function that returns the id
// rest of the class definition
//...
};
#endif // end of define A_H
//a.h file
#ifndef A_H
#define A_H
class A{
static int myID;
int member;
public:
A();
A(A&); //copy c-tor
int id(); // function that returns the id
// rest of the class definition
//...
};
#endif // end of define A_H
To copy to clipboard, switch view to plain text mode
and the cpp file:
//a.cpp
#include "a.h"
int A::myID = 0;
A::A(){
myID++;
}
A::A(A& ref){ //implementation of copy constructor
// here you copy the members from the ref object passed to the constructor
member = ref.member; //just an example here member is uninitialized... you need to take care of all the data members
myID++; // and increment the static variable...
}
int A::id() {
return myID;}
//a.cpp
#include "a.h"
int A::myID = 0;
A::A(){
myID++;
}
A::A(A& ref){ //implementation of copy constructor
// here you copy the members from the ref object passed to the constructor
member = ref.member; //just an example here member is uninitialized... you need to take care of all the data members
myID++; // and increment the static variable...
}
int A::id() {
return myID;}
To copy to clipboard, switch view to plain text mode
Bookmarks