Yvonne Yvonne - 29 days ago 15
C++ Question

Using header file in C++ program

I have some question for coding C++ program with header file.

This is my header.h file :

#include <iostream>

using namespace std;

class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);

private:
double width;
double length;
double area;
double factor;
};


And this is my Question1.cpp file which store all the methods:

#include <iostream>

using namespace std;

class Rectangle
{
public:
Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}

double Rectangle::get_perimeter()
{
return ((width * 2) + (length * 2)) ;
}

double Rectangle::get_area()
{
return (width * length);
}

void Rectangle::resize(double factor)
{
width *= factor;
length *= factor;
}

private:
double width;
double length;
double area;
double factor;
};


And lastly, here is my main method.cpp :

#include <iostream>
#include "header.h";

using namespace std;

int main()
{
Rectangle rectangle1(2.5,7.0);
cout << rectangle1.get_perimeter();
cout << rectangle1.get_area();

system("PAUSE");
return 0;
}


However, when I try to run the program, the system told me that there was build errors and unresolved externals which I have no idea why is it so. Could somebody please help me fix it?

Thanks in advance.

Answer

Your implementations should not look like

class Rectangle
{
public:
Rectangle(double width, double length) { .... }

but like

Rectangle::Rectangle(double width, double length) : width(width), length(length) {}

You need to include header.h in the implementation .cpp file and in any file that needs the definition of the Rectangle class. You also need include guards in your headers. And do not put using namespace std in a header. In fact, don't put it anywhere.

Comments