Overloading << Issue

This is a discussion on Overloading << Issue within the C++ Programming forums, part of the General Programming Boards category; It is to my understanding to overload the output operator (<<) you must declare the function as standalone - OK. ...

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    32

    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..

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    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.
    Last edited by 7stud; 10-27-2005 at 02:24 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. overloading <<
    By msshapira in forum C++ Programming
    Replies: 2
    Last Post: 05-06-2009, 02:11 PM
  2. Overloading fstream's << and >> operators
    By VirtualAce in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2007, 03:17 AM
  3. Overloading the << operator.
    By antex in forum C++ Programming
    Replies: 5
    Last Post: 05-31-2005, 01:37 AM
  4. << and >> overloading
    By Armatura in forum C++ Programming
    Replies: 2
    Last Post: 12-07-2003, 05:19 PM
  5. Overloading << for my class
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-30-2003, 02:45 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21