I'm trying to write an overloaded stream insertion operator for a class who's only member is a vector. It's a vector of Point
s, which is a struct
containing two double
s.
I figure what I want is to insert user input (a bunch of double
s) into a stream that I then send to a modifier method. I'm working off other stream insertion examples such as:
std::ostream& operator<< (std::ostream& o, Fred const& fred)
{
return o << fred.i_;
}
but when I try something similar:
istream & operator >> (istream &inStream, Polygon &vertStr)
{
inStream >> ws;
inStream >> vertStr.vertices;
return inStream;
}
I get an error "no match for operator >>
etc etc." If I leave off the .vertices
, it compiles, but I figure that's not right. (By the way, vertices
is the name of my vector <Point>
.) And even if it is right, I don't actually know what syntax to use in my program to use it, and I'm also not 100% sure on what my modifier method needs to look like.
Here's my Polygon
class:
//header
#ifndef POLYGON_H
#define POLYGON_H
#include "Segment.h"
#include <vector>
class Polygon
{
friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr);
public:
//Constructor
Polygon(const Point &theVerts);
//Default Constructor
Polygon();
//Copy Constructor
Polygon(const Polygon &polyCopy);
//Accessor/Modifier methods
inline std::vector<Point> getVector() const {return vertices;}
//Return number of Vector elements
inline int sizeOfVect() const {return (int) vertices.capacity();}
//add Point elements to vector
inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);}
private:
std::vector<Point> vertices;
};
#endif
//Body
using namespace std;
#include "Polygon.h"
// Constructor
Polygon::Polygon(const Point &theVerts)
{
vertices.push_back (theVerts);
}
//Copy Constructor
Polygon::Polygon(const Polygon &polyCopy)
{
vertices = polyCopy.vertices;
}
//Default Constructor
Polygon::Polygon(){}
istream & operator >> (istream &inStream, Polygon &vertStr)
{
inStream >> ws;
inStream >> vertStr;
return inStream;
}
Sorry to be so vague; a lecturer has just kind of given us a brief example of stream insertion and then left us on our own.