Newbie alert: I'm learning about how to use multiple files to better organize code. Our book says that the class definitions go in a .h file while the class functions themselves go in an implementation file (.cpp or .cxx). Easy enough.
I have created a class called "circle". Following the above structure, I created two files called circle.h and circle.cpp. In the circle.cpp file, I have a line "#include circle.h".
Where does int main() go? I put it in a third file called "main.cpp". In that file, I added "#include circle.cpp (I also tried #include circle.h). In int main(), I have a line that creates a new circle (circle my_circle()), but it won't compile. I get an error message that says: "
from main.cpp
expected unqualified-id before '}' token
In function int main()':
circle was not declared in this scope
expected ';' before "my_circle"
Can somebody set me straight about how to integrate these various files? Thanks.
#include "Circle.h"
Circle::Circle() : radius(0) //initialize radius to 0
{
}
Circle::Circle(constunsignedlong& radius) : radius(radius) //initialize radius to the given parameter
{
}
Circle(const Circle& from) : radius(from.radius) //copy the radius from the other circle
{
}
Circle& Circle::operator=(const Circle& from)
{
radius = from.radius;
}
void Circle::SetRadius(constunsignedlong& newRadius)
{
radius = newRadius;
}
unsignedlong Circle::GetRadius()
{
return(radius);
}
Circle::~Circle() //If you used pointers with new or new[] in the constructors, use delete or delete[] here
{
}
#include <iostream>
usingnamespace std;
#include "Circle.h" //The other .cpp file provides the definitions, the linker will link it all together
int main()
{
Circle a (5); //makes a circle with radius 5
cout << a.GetRadius() << endl;
Circle b (a); //b copies the radius from a
cout << b.GetRadius() << endl;
Circle c = a; //in this case it calls the copy constructor and not operator=
cout << c.GetRadius() << endl;
b.SetRadius(7); //changes b's radius to 7;
cout << b.GetRadius() << endl;
c = b; //this calls operator=
cout << c.GetRadius() << endl;
//Hold the window open until you press enter
cin.sync();
cin.ignore();
}