C++ header file creating given main.cpp and Line.cpp Instructions: Write a heade
ID: 3864261 • Letter: C
Question
C++ header file creating given main.cpp and Line.cpp
Instructions:
Write a header for a nested class called Point inside a class called Line. We have already included the main function and the classes definition in the moodle code runner. So you have to just write a header file for the classes. The Line class basically finds out the distance between points (x1,y1) and (x2,y2). We have also attached the main function and the Line.cpp in the moodle just for your reference. You can a look at it and build your class header with help of it.
Note: The class point should be nested inside the class line and the class point should contain necessary variables and a function called print which prints the values of x and y for the Point object.
The main.cpp file looks like this
Line.cpp looks like this
My naive header file implementation.
#ifndef LINE_H
#define LINE_H
class Line
{
public:
double num;
class Point
{
public:
double x;
double y;
double print(double num);
};
double end0;
double end1;
Line();
Line(double, double, double, double);
double length();
};
#endif
Explanation / Answer
The solution contains 3 files : main.cpp, Line.h and Line.cpp. Following are the file contents :-
The file main.cpp is :-
#include <iostream>
#include "Line.h"
using namespace std;
int main()
{
Line myLine (2.1, 3.2, 4.5, 5.6);
cout<< "I built a line with points: ";
myLine.end0.print();
cout<< " and ";
myLine.end1.print();
cout<< endl;
cout<<"The length of my line is: "<< myLine.length() << endl;
return 0;
}
The file Line.h is :-
//Header file that defines class Line and class Point. Class Point is nested inside class Line.
#ifndef LINE_H
#define LINE_H
#include <iostream>
using namespace std;
class Line
{
public:
double num;
class Point
{
public:
double x;
double y;
void print() { cout << "x = "<< x << " " << "y = "<< y; }
};
Point end0; // Defines first point of a line
Point end1; // Defines last point of a line
Line(double x1, double y1, double x2, double y2); // Constructor that assigns (x,y) values to first and last points of a line
double length();
~Line();
};
#endif
The file Line.cpp is :-
#include <cmath>
#include "Line.h"
Line::Line(double x1, double y1, double x2, double y2)
{
end0.x=x1;
end0.y=y1;
end1.x=x2;
end1.y=y2;
}
double Line::length()
{
return (sqrt(pow(end1.x-end0.x,2)+pow(end1.y-end0.y,2)));
}
Line::~Line()
{
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.