I have a class which works fine when I use a separate header file, class file, and main file. However, I was told I needed to put the class file and main file together, but I cannot figure out what is wrong. I keep getting an error:
error LNK2001: unresolved external symbol "private: static int Circle2D::numberOfCircles" (?numberOfCircles@Circle2D@@0HA)
Here is the combined file (class defn. and main):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#define PI 3.14159265
#include "Math.h"
#include <iostream>
using namespace std;
#include <string>
// This is the Circle2D class.
class Circle2D
{
public:
// Construct a circle object - DEFAULT no arg.
Circle2D()
{
radius = 1;
x = 0;
y = 0;
cName = "Circle";
numberOfCircles++;
}
// Return the number of circle objects
static int getnumberOfCircles()
{
return numberOfCircles;
}
// Destruct a circle object
Circle2D::~Circle2D()
{
numberOfCircles--;
}
private:
double x, y; // The coords of center of circle.
double radius; // The radius of the circle.
string cName; // The name of the circle.
static int numberOfCircles; // Store the number of circles.
};
// Here we are going to test the Circle2D class.
int main()
{
// Create a circle of radius on at origin.
Circle2D *pC1 = new Circle2D();
// Create a circle of radius 5 at origin.
Circle2D *pC2 = new Circle2D();
cout << Circle2D::getnumberOfCircles() << endl;
// clean up.
delete pC1;
delete pC2;
return 0;
}
|
When I was using three files it was like this:
In the header file, I had a public function declaration like this:
static int getnumberOfCircles();
and a private data member:
static int numberOfCircles;
Then in the class file, I had:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include "Circle2D.h"
int Circle2D::numberOfCircles = 0;
Circle2D::Circle2D()
{
radius = 1;
x = 0;
y = 0;
numberOfCircles++
}
int Circle2D::getnumberOfCircles()
{
return numberOfCircles;
}
|
But when I combined the files, I cannot get rid of the error. So, what did I do wrong? I don't know where to initialize the data member numberOfCircles in the combined file, I think this is why I am getting the error.
Thank you!