Thread: Overloading Operators

  1. #1
    Registered User
    Join Date
    Aug 2001

    Question Overloading Operators

    I want to write a vector class:

    class fVECTOR3 {

    //overloaded operators should come here//

    float X[3];

    So, I tried to overload +, -, *, =, == ... but I didn't get the wanted results (but at least my program compiled!!!).

    Can someone be so nice and overload the '-' operator for this class (As soon as one operator works, I can do all the others, too - I guess).
    (If someone could even overload =, that would be even nicer ;-)

    Here is a short code example of what the class should be capable of:

    fVECTOR3 v1, v2, v3;
    v1 = fVECTOR3(1.0f,2.0f,3.0f);
    v2 = fVECTOR3(2.0f,3.0f,4.0f);
    v3 = v2 - v1;
    printf("x = %f\n", v3.x[0]);

  2. #2
    Define what you mean by the fVecotr class. A vector is often based on a self-expanding array like this:

    class Vector
    int size
    int capacity
    float array[]

    The [] operator is often overloaded to allow the vector instance to act like the underlying array. That is if Vector vector1; then vector1[i] == vector1.array[i];

    You need to define what you mean by adding and substracting a vector/array. Do you mean add all the contents of one vector to another such that if vector1 had size 3 and vector2 had size 11 then vector3 = vector1 + vector2 will have size 14? For subtraction do you mean vector3[i] = vector1[i] - vector2[i] if size of vector1 >= size of vector2?? or what?

    BTW without the overloaded [] it would be:

    vector3.array[i] = vector1.array[i] - vector2.array[i];

    or within the overloaded operator definition it might be this:

    vector3.array[i] = this->array[i] - rhs.array[i];

    or vector3[i] = *this[i] - rhs[i]; if the [] is overloaded.

    Once you have those definitions, then code can probably be developed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about overloading operators
    By *DEAD* in forum C++ Programming
    Replies: 9
    Last Post: 05-08-2008, 10:27 AM
  2. Replies: 16
    Last Post: 10-27-2007, 12:42 PM
  3. Overloading fstream's << and >> operators
    By VirtualAce in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2007, 03:17 AM
  4. operators overloading
    By waqasriazpk in forum C++ Programming
    Replies: 1
    Last Post: 07-26-2002, 01:05 AM
  5. Overloading operators...
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2001, 08:24 PM