简体   繁体   中英

How to create operator*(double) for multiplying on both the left and right hand side?

I'm trying to figure out how to write an overloaded operator for my Vector2d class that allows me to multiply by a scalar on both the left and right sides.

class Vector2d
{
    double _x;
    double _y;

public:
    Vector2d(double x = 0, double y = 0) :_x(x), _y(y) {}

    Vector2d operator*(const double s) const
        { return Vector2d(_x * s, _y * s); }

    friend Vector2d operator*(const double s, const Vector2d& v);
};

Vector2d operator*(const double s, const Vector2d& v)
{
    return Vector2d(v._x * s, v._y * s);
}

If I only define the member operator*, my object can be multiplied on the right by a scalar but not the left. If I add the friend function operator*, I get an error when I compile:

Vector2D.h:61: multiple definition of `Gf::operator*(double, Gf::Vector2d const&)'
Vector2D.h:61: first defined here
Vector2D.h:61: multiple definition of `Gf::operator*(double, Gf::Vector2d const&)'

What's the right way to do this?


I was putting the operator* function in the header file. Once I moved it to the .cpp, it compiled correctly.

It looks like your file has been included multiple times, most compilers support #pragma once these days. You can also use a header guard (check for a token's definition before defining it along with the rest of your header) :

#ifndef VECTOR_2D
#define VECTOR_2D

class Vector2d
{
    double _x;
    double _y;

public:
    Vector2d(double x = 0, double y = 0) :_x(x), _y(y) {}

    Vector2d operator*(const double s) const
        { return Vector2d(_x * s, _y * s); }

    friend Vector2d operator*(const double s, const Vector2d& v);
};

Vector2d operator*(const double s, const Vector2d& v)
{
    return Vector2d(v._x * s, v._y * s);
}

#endif // VECTOR_2D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM