Thread: Overloading << for my class

  1. #1

    Overloading << for my class

    I'm making a general "logger" class, and for this i am using the c++ ostream class, because of the ease of << use. I will need to overload the << operator, so that people outside the class can use "logger_obj << "Hello" << endl;". I was reading about this, and the site i am reading says that something has to be a "friend" to be able to use this operator when it is overloaded. What does this mean, and why is it, or is ut untrue?

    Example given:
    Code:
    __friend ostream& operator << ( ostream& s, ED& d);_
    _
    __ostream& operator << (ostream& s, ED& d ) {_
    ___s << d.feet << "\'=" << d.inches << '\"';_
    ___return s;_
    __}
    ~Inquirer
    Last edited by Inquirer; 04-29-2003 at 09:41 PM.
    Compilers:
    GCC on Red Hat 8.1 (Primary)
    GCC on Mac OS X 10.2.4 (Secondary)

    Others:
    MinGW on XP

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    110
    What you are reading about is for using the following
    Code:
      ostream << logger_obj;
    This does not sound what you are wanting to do. What you are wanting to do is overload the specific operators inside of your class. This would be done as follows. ( as a function in your class definition).

    Code:
      logger_obj &operator << ( string theText );
    This will allow for the following code to be used by others in the following fashion.

    Code:
      logger_obj << "Hello" << std::endl;
    Hope that this helps you with your problem.

    Later,
    WebmasterMattD
    WebmasterMattD.NET

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading templated class operators
    By Artemis0583 in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2006, 12:30 PM
  2. Replies: 7
    Last Post: 05-26-2005, 10:48 AM
  3. overloading the division operator with Integer Class
    By silk.odyssey in forum C++ Programming
    Replies: 3
    Last Post: 05-17-2004, 06:59 PM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  5. Problems: Operator overloading.
    By Dual-Catfish in forum C++ Programming
    Replies: 17
    Last Post: 06-18-2002, 06:38 PM