CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2009
    Posts
    1

    Problem trying to overload Operator

    So, I'm trying to overload the * operator so that I can multiply two vectors (math vectors, not data structure vectors) together.

    Here is my vector class.

    class Vec{
    float x;
    float y;
    float z;

    public:

    Vec(){}

    Vec(float X, float Y, float Z){
    x = X;
    y = Y;
    z = Z;
    }

    Vec operator*(Vec b){
    return Vec(this->x*b.x, this->y*b.y, this->z*b.z);
    }

    Vec operator*(int a){
    return Vec(a*this->x, a*this->y, a*this->z);
    }

    Vec operator-(Vec b){
    return Vec(this->x-b.x, this->y-b.y, this->z-b.z);
    }

    float getX(){
    return x;
    }

    float getY(){
    return y;
    }

    float getZ(){
    return z;
    }

    void setX(float newX){
    x = newX;
    }

    void setY(float newY){
    y = newY;
    }

    void setZ(float newZ){
    z = newZ;
    }
    };

    Later In my code, I use this:

    Vec R = 2 * dotProduct(L, Normal) * Normal - L;

    Where L and Normal are Vec and dotProduct() returns a Vec.
    Here is the error I keep getting:
    error C2677: binary '*' : no global operator found which takes type 'Vec' (or there is no acceptable conversion)

    Could someone please help me with this?

  2. #2
    Join Date
    Dec 2008
    Posts
    144

    Re: Problem trying to overload Operator

    If any operator function is a member of a class the left operand of this operator must always be an instance of this class.
    As you can see in this expression
    Code:
     
    Vec R = 2 * dotProduct(L, Normal)
    the left operand is int.
    So you should provide a global operator, which takes an integer value as a first argument and a Vec object as a second argument.
    Code:
    Vec operator*(int a, const Vec &b)
    It can be a friend of your class.

  3. #3
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Problem trying to overload Operator

    Or rewrite the calculation as dotProduct() * 2 so Vec is first.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured