operator overloading in c++

Discussion in 'Archived Threads 2001-2004' started by felix_suwarno, Sep 13, 2002.

  1. felix_suwarno

    felix_suwarno Screenwriter

    Joined:
    Dec 2, 2001
    Messages:
    1,523
    Likes Received:
    0
    Trophy Points:
    0
    somebody please help me on this simple problem. it is about operator overloading. i understand the concept, but i am not sure how to write it.

    the following is a method to add two VECTOR object. the vector uses 3 different variables. say, vector A is (1,3,5). it is a vector in 3D space ( x, y and z coordinate ). i need to write a method that adds two vector objects ( v and w ) with operator overloading.

    vector operator+(const vector& v, const vector& w)
    {
    vector z;
    z[0] = v[0] + w[0];
    z[1] = v[1] + w[1];
    z[2] = v[2] + w[2];

    return z;
    }

    is that how it is written? if not, let me know how to do it properly.

    BIG thanks in advance
     
  2. Gary King

    Gary King Second Unit

    Joined:
    Apr 13, 1999
    Messages:
    479
    Likes Received:
    0
    Trophy Points:
    0
    Unless you've previously defined operator[] for the vector class, or you've typedef'd vector as an array, you won't be able to access data like that.

    In general, my vectors look like this:

    struct vector {
    union {
    struct {
    float x, y, z; };
    float v[3]; };
    };

    And then I can access the elements of any vector with .x, .y, .z or .v[0], .v[1], and .v[2].
     
  3. felix_suwarno

    felix_suwarno Screenwriter

    Joined:
    Dec 2, 2001
    Messages:
    1,523
    Likes Received:
    0
    Trophy Points:
    0
    oh, the struct definition is already written. all i am supposed to do is to fill the blanks. this course is not intro to c++. i just need to know how operator overloading works, because i still dont have a strong grasp about it.
     
  4. Steven K

    Steven K Supporting Actor

    Joined:
    Jan 10, 2000
    Messages:
    830
    Likes Received:
    0
    Trophy Points:
    0
    Felix,
    Unfortuntately I dont have time to get into the intrcacies of Operator Overloading now. However, check out the section in the C++ FAQ Lite. Operator Overloading
     

Share This Page