operator overloading

This is a discussion on operator overloading within the C++ Programming forums, part of the General Programming Boards category; how do you perform operator overloading using binary operators? Yes, Yes it is a homework problem, it is just that ...

  1. #1
    I'm Back
    Join Date
    Dec 2001
    Posts
    556

    operator overloading

    how do you perform operator overloading using binary operators?

    Yes, Yes it is a homework problem, it is just that i cant understand overloading bit..

    isn't this a binary operator statement -->

    a*b;
    a+b; etc

    how do you overload that?


    *edit*
    post# 69 yay!!
    Last edited by ihsir; 02-06-2002 at 09:53 AM.
    -

  2. #2
    Unregistered
    Guest
    operator overloading is discussed in the following link:

    http://www.stud.fim.ntnu.no/~oystesk/CPP/htm/ch10.htm

    The simplist declaration of an overloaded binary operator for class T would be something like this:

    class T
    {
    public:
    //default constructor assigns value of 0 to data
    //single parameter cconstructor assigns input to data
    int data;
    T T::operator+(const T &)
    };

    with definition like this:

    T T::operator+(const T & rhs)
    {
    T temp;
    temp.data = data + rhs.data;
    return (temp);
    }

    and used in program like this:

    int main()
    {
    T example1(3), example2(18);
    T result;
    result = example1 + example2;
    cout << result.data;
    return 0;
    }

    But read the chapter for a more sophisticated discussion and other examples.

  3. #3
    I'm Back
    Join Date
    Dec 2001
    Posts
    556
    great link Unregistered, but is there a way to do it without using of classes,constructors etc

  4. #4
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    No, you can't create global overloads for the binary operators.

  5. #5
    Unregistered
    Guest

    Use a friend

    if you do not want it to be a class member.
    try this: friend T operator + (int n, T whatever )

Popular pages Recent additions subscribe to a feed

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