开发者

How to implement an operator usable before an instance (pre position)

开发者 https://www.devze.com 2023-03-19 03:46 出处:网络
I have a class with the operator* taking a scalar as argument, that allow me to perform the multiplication of an instance of my class with a scalar. I\'d like to be able to multiply a scalar by an ins

I have a class with the operator* taking a scalar as argument, that allow me to perform the multiplication of an instance of my class with a scalar. I'd like to be able to multiply a scalar by an instance of my class (inverse order with the same result). How can I do that ?

Here an example :

class Vector3d
{
public:
    Vector3d(double x, double y, double z) {
        v[0] = x; v[1] = y; v[2] = z;
    }

    template<typename T>
    Vector3d operator*(const T s) const {
        return( Vector3d( v[0] * s, v[1] * s, v[2] * s)); 
    }

//protected: example purpose
    double v[3];
};

main()
{
    double scalar = 2.0;
    Vector3d vector(1.0,2.0,3.0);
    Vector3d v2 = vector*scalar;
    //This is the operation I want to be able to perform !
    //Vector3d v3 = scalar*vector; 
    return 0;
}

I tried to implement it like we do with ostream<< operator without success ...

template<typename T>
Vector3d operator*(T& s, const Vector3d &v)
{
    return( Vector3d( v[0] * s, v[开发者_开发百科1] * s, v[2] * s));
} 


You must declare your operator* as a nonmember function (outside class) with inverse argument order and call the other one from it

template<typename T>
Vector3d<T> operator*(T& s, const Vector3d<T> &v)
{
    return Vector3d(v.v[0] * s, v.v[1] * s, v.v[2] * s);
} 
template<typename T>
Vector3d<T> operator*(const Vector3d<T> &v, T& s)
{
    return s * v; //call the other overload
} 

And don't forget specifying the template parameters:

Vector3d<T>
        ^^^

One more issue... Why take T& istead of const T& or just T? In current form you're preventing rvalues to be passed. For example, this wouldn't compile:

Vector3d<int> v;
v*3; //3 isn't an lvalue, cannot bind to a nonconst reference


It is best to do operator overloading outside of the class, that gives you maximum flexibility.

// This compiles fine.

class Vector3d
{
public:
    Vector3d(double x, double y, double z) {
        v[0] = x; v[1] = y; v[2] = z;
    }

    double v[3];
};

template<typename T>
Vector3d operator*(const T& s, const Vector3d &v) 
{
    return( Vector3d( v.v[0] * s, v.v[1] * s, v.v[2] * s)); 
}

int main(int argc, char **argv)
{

    double scalar = 2.0;
    Vector3d vector(1.0,2.0,3.0);
    Vector3d v3 = scalar * vector; 
    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号