Thread: friend functions

  1. #1
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788

    friend functions

    Umm, my problem is this.
    I have a friend function in my string class.
    The class declaration in a .h file. The class implementation is in
    a .cpp file.
    If i define the friend function in the .cpp file i get this error :

    << is not a member of String

    I want to overload the '<<' operator to provide printing for my
    class. Here's what i'm doing:
    Code:
    //This is the .h file
    #include <iostream.h>
    
    class String
    {
    public:
          friend ostream& operator<<(ostream&, String&);
          //.....
          //.....
    private:
         char*  lpzstr;
    };
    Then I define the function in the .cpp file like this :
    Code:
    ostream& operator<<(ostream& o, String& newStr)
    {
             return o << newStr.lpzstr;
    }
    Where should i define friend functions OR what am I doing
    wrongly?

  2. #2
    Registered User
    Join Date
    May 2002
    Posts
    317
    Try this:
    Code:
    ostream& operator<<(ostream& o, String& newString)
    {
                o<<newString.lpzstr;
                return o;
    }

  3. #3
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    Well what do you know, my original code works all of a sudden!!

    I think it was perhaps my compiler(MSVC++ 6) OR it could be this
    Vsual Assist Intellisense upgrade that's messing everything up!

    But thanks anyway for your reply, i appreciate it vey much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Friend Functions
    By rculley1970 in forum C++ Programming
    Replies: 5
    Last Post: 03-25-2007, 03:25 AM
  2. Static member functions more efficient?
    By drrngrvy in forum C++ Programming
    Replies: 6
    Last Post: 06-16-2006, 07:07 AM
  3. Friend template functions
    By lyx in forum C++ Programming
    Replies: 4
    Last Post: 10-02-2003, 01:11 PM
  4. inline friend functions.
    By sean in forum C++ Programming
    Replies: 2
    Last Post: 01-03-2002, 12:37 PM
  5. Visual C++ and friend functions giving errors
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 11-04-2001, 06:55 PM