Overloading in C++

Discussion in 'Computer Gaming Forum' started by jimmyv, Mar 21, 2010.

  1. jimmyv

    jimmyv Spirited Member

    Joined:
    May 21, 2009
    Messages:
    119
    Likes Received:
    0
    Well, my OOP teacher decided to assign a project to overload operators in c++. This isnt really an issue, what IS an issue is that the school teaches java, so now I get stuck with an assignment to do something in c++ with absolutely NO introduction on how to do. She prints out the worst piece of shit example from a book. I know programming I level c++, but I'm missing three semesters worth of c++ knowledge.

    So to the point, does anyone know of a very good online tutorial on how to overload operators? I would buy a book since c++ would be something I would need to know eventually, but(as made proof by recent threads), I'm strapped for cash.


    BTW....if anyone has anything related to overloading operators to work on sets....you'll get the biggest cookie evar!!!
     
    Last edited: Mar 21, 2010
  2. graphique

    graphique Enthusiastic Member

    Joined:
    Oct 17, 2007
    Messages:
    578
    Likes Received:
    25
    Using + as an example, you can either make a class method:

    MyClass MyClass::eek:perator+(MyClass &A)

    Which returns the result of adding A to "this",

    Or a global function:

    MyClass operator+(MyClass &A, MyClass &B)

    Which returns the result of adding A to B.

    You can make the parameters and return type anything you want, but the operators still have to have the same number of arguments as the original (addition always has to be a binary operation, etc.)
    Once you have this, you can just go ahead and use this operator on objects of your class type in your code.
    One thing to be aware of: the assignment operators like +=, -=, etc (which can't be defined globally) typically are expected to return a reference to "this".

    EDIT: as for sets, I presume you're going to want to do union, intersection, etc. Then all you need to do is (for example) write an operator+ that unions your two set data structures together and returns the result.
     
  3. mairsil

    mairsil Officer at Arms

    Joined:
    Apr 20, 2005
    Messages:
    3,425
    Likes Received:
    153
    No offense, but Google is your friend. Operator overloading is problematic for a lot of people to pick up, so a tutorial that works great for one person might not work well for another.
     
  4. Infrid

    Infrid Rapidly Rising Member

    Joined:
    Jan 12, 2006
    Messages:
    86
    Likes Received:
    1
    get Thinking in C++ Volume 1, there is a chapter dedicated to this part of language.

    www.mindview.net
     
sonicdude10
Draft saved Draft deleted
Insert every image as a...
  1.  0%

Share This Page