-
Overloading << Issue
It is to my understanding to overload the output operator (<<) you must declare the function as standalone - OK.
And also if you want to access the private data you need to make it a "friend" of the class - OK.
But when I compile, I get a undeclared identifier error.. Any help would be appreciated.
Friend declaration in my .h file under public:
Code:
friend ostream& operator<<(ostream&, GList);
Stand-alone function (end and list are private data members):
Code:
ostream& operator<<(ostream& out, GList list)
{
for(int i = 0; i < end; i++)
{
out << list[i];
}
return out;
}
Output errors:
error C2065: 'end' : undeclared identifier
error C2676: binary '[' : 'GList' does not define this operator or a conversion to a type acceptable to the predefined operator
Thanks in advance..
-
See if this helps:
Code:
#include <iostream>
using namespace std;
class GList
{
private:
int end;
int* pArray;
public:
GList(int size, int* anArray)
{
end = size;
pArray = anArray;
}
friend ostream& operator<<(ostream&, const GList&);
};
ostream& operator<<(ostream& out, const GList& list)
{
for(int i=0; i<list.end; i++)
{
out<<list.pArray[i]<<endl;
}
return out;
}
int main()
{
int size = 3;
int arr[] = {10, 20, 30};
GList myList(size, arr);
cout<<myList;
return 0;
}
Note: you should make the GList parameter a reference to avoid having to copy the object for the function, and you should make it a const since the function doesn't need to change the GList object.