双向运算符重载

时间:2015-05-10 16:46:09

标签: c++ operator-overloading

代码

Vector.h

friend Vector& operator* (const double &factor, const Vector &v);
friend Vector& operator* (const Vector &v,const double &factor);

Vector.cpp

Vector& operator *(const double &factor, Vector &v){
    v.x=v.x*factor;
    v.y=v.y*factor;
    return v;
}
Vector& operator* (const Vector &v,const double &factor){
    return factor * v;
}

对于某些读取,我在Vector.cpp文件中收到错误, Vector& operator* (const Vector &v,const double &factor) -function

  

对`operator *(double const&,Vector const&)'

的未定义引用

我做错了什么......?

1 个答案:

答案 0 :(得分:1)

正如我的评论中所提到的,错误发生了,因为你的函数声明和定义签名不同。

无论如何,如果有一个独立的运算符函数,我们希望获得一个新的Vector实例,而不是获得对传递的实例的引用。

声明/定义您的运算符函数,如下所示:

friend Vector operator* (const Vector &v,double factor);
friend Vector operator* (double factor, const Vector &v);

Vector operator *(double factor, const Vector &v) {
    Vector result = v;
    result.x=result.x*factor;
    result.y=result.y*factor;
    return result;
}

Vector operator* (const Vector &v,double factor) {
    return factor * v;
}