Reputation: 13
I am facing a problem whereby I have already done my operator <<
but it doesn't work for some reason. I tried countless ways and the one below made the most sense to me. But still failed. Can anyone show me the proper way to overload (*this)[index]
in this specific instance(Refer to class VisiblePolygon)? Class Polygon will consist of the operator <<
to the class VisiblePolygon. Can't find a solution for this specific case. Hence I'm here. Thanks!
Compile error:
In function ‘std::ostream& operator<<(std::ostream&, const Polygon&)’:
polygon.h:103:8: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Object::PointType’)
os <<p.mpt[i];
~~~^~~~~~~~~~
My code:
#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <cmath>
class Polygon : public Point
{
private:
Object::PointType *mpt; //An array of points
int msize;
public:
PointType& operator[](int index) const
{
return mpt[index];
}
Polygon(const PointType* points, int npoints);
Polygon(PointType* points, int npoints, float depth) //constructor
: Point(*points,depth),
mpt{new Object::PointType[npoints]},
msize(npoints)
{
for(int i = 0; i < msize; ++i)
{
mpt[i] = points[i];
}
}
Polygon center()
{
//..
}
float x()
{
//...
}
float y()
{
//...
}
int size() const
{
return msize;
}
virtual void render() const
{}
friend std::ostream& operator<<(std::ostream& os, const Polygon& p)
{
for (int i = 0; i < p.msize; ++i)
{
os <<p.mpt[i];
return os;
}
}
};
class VisiblePolygon : public Polygon
{
public:
VisiblePolygon(const Object::PointType* points, int size) :
Polygon(points, size)
{
}
void render() const override
{
std::cout << "Polygon with vertices: ";
for (int index = 0; index < size(); ++index)
{
std::cout << (*this)[index] << " ";
}
std::cout << std::endl;
}
};
Upvotes: 1
Views: 61
Reputation: 85266
The error
In function ‘std::ostream& operator<<(std::ostream&, const Polygon&)’: polygon.h:103:8: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘Object::PointType’)
basically says "OK you have operator <<
for Polygon
, now you need one for PointType
as well".
Unrelated, but return os;
should probably be outside the loop.
Upvotes: 2