I just started looking at structs in C++ and thought I might try and figure out how to overload the stream insertion operator to take and object of Line (which itself contains objects of Point). I think I need some sort of declaration of overloading in Line? and possibly point? I found some similiar questions but to be honest I can’t figure it out at all.
It’s a very simple program so hopefully someone could take the time to look at it and explain to me how I should be going about it?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::istream;
//define Point & Line type
struct Point{
float x, y;
};
struct Line{
Point p1, p2;
istream& operator>>( istream& in, const Line& line); //something like this here?
};
//function declarations
Point calcMidpoint(const Line& rline);
//operator overload
istream& operator>>( istream& in, const Line& line){
in >> line.p1.x >> line.p1.y >> line.p2.x >> line.p2.y;
return in;
}
//MAIN
int main(){
Line line;
cout << "please enter one pair of x and y values followed by another like so (x1 y1 x2 y2): ";
cin >> line;
//get midpoint of line
Point mp;
mp = returnMidpoint(line);
cout << "The Midpoint is.. (" << mp.x << " " << mp.y << ")" <<endl;
return 0;
}
//can be used in a large expression at the expence of creating temp instances
Point calcMidpoint(const Line& rline){
Point midpoint;
midpoint.x = (rline.p2.x + rline.p1.x) / 2;
midpoint.y = (rline.p2.y + rline.p1.y) / 2;
return midpoint;
}
Binary operators can only be defined as member functions if the first operand is of the type of the class. Since this isn’t the case (the first operand is
std::istream&), you must define a free function:It might be useful to declare this function a
friendinside your class so it can access private members.