Reputation: 1
When trying to attempt to overload operator<<
in my shape.cpp
, it can't seem to recognize the variables within the class, even though it is a friend
of the class.
My .cpp
file:
#include "Shape.h"
ostream& operator << (ostream& cout, const Shape& shapes)
{
for (int i = 0; i < points.size(); i++) //points is undefined
{
cout << points[i] << endl;
}
}
My .h
file:
#include <vector>
#include "Point.h"
#pragma once
using namespace std;
class Shape
{
friend ostream& operator << (ostream& cout, const Shape& shapes);
private:
vector <Point> points; //Ordered list of vertices
};
I already used the same overload for my point
class and it worked fine.
Upvotes: -3
Views: 290
Reputation: 118350
A friend
function is not a class member. It can be treated as any other non-class function. Except that, because it's a friend
, it has access to its private members:
ostream& operator << (ostream& cout, const Shape& shapes)
{
for (int i = 0; i < shapes.points.size(); i++)
{
cout << shapes.points[i] << endl;
}
}
It should now be clear that the object gets passed in as the shapes
parameter. Well, it's points
member must, therefore, be shapes.points
.
However, we can do even better than that. How about using range iteration?
ostream& operator << (ostream& cout, const Shape& shapes)
{
for (auto &v:shapes.points)
{
cout << v << endl;
}
}
Upvotes: 1