accessing private data to initialize object using overloaded operator

Im needing some help to access a private data member while using an overloaded operator.

#ifndef Shape_hpp
#define Shape_hpp
using namespace std;
#include <iostream>
#include <stdio.h>
#include<iomanip>

class Shape{
public:
virtual void print()=0;
};

#endif /* Shape_hpp */


class Point: public Shape
{ friend ostream &operator<<( ostream &, const Point & );
friend istream &operator>>(istream &, Point &);

private:
double x;
double y;
public:
Point();
Point(double,double);
~Point();
void print();
double getX()const;
double getY()const;
void setX(double);
void setY(double);

};

#include "Shape.h"
#include "Point.h"
#include <stdio.h>
class Line: public Shape
{
friend ostream &operator<<( ostream &, const Line & );
friend istream &operator>>(istream &, Line &);
private:
Point p1;
Point p2;
public:
Line(Point,Point);
~Line();
Point getp1()const;
Point getp2()const;
void setp1(Point);
void setp2(Point);
void print();
};

//this is line.cpp

istream &operator>>(istream& input, Line & line){
input.ignore();
input>>setw(1)>>line.p1.x;
input.ignore();
input>>setw(1)>>line.p1.y;
input.ignore();
return input;

im trying to input doubles into a lines p1 and p2. The code above tells me that x and y are private and that I cannot access it directly. I was asked to specifically use overloaded insertion operators to initialize the objects.

Hello Matteo1230,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



That is because only a public member function can access a private member of the class. It looks like what you want is input>>setw(1)>>line.setp1(x); not input>>setw(1)>>line.p1.x;. I am not sure, but the "setw(1)" might be a problem.

Andy
Hello Matteo1230,

When I tried looking at the code that you posted I have to ask if this is all in 1 file or separate files?

As is it makes no sense.

Andy
Topic archived. No new replies allowed.