在C++中重载乘法运算符的正确方法(双向)



我设法理解了如何将重载运算符实现为成员函数。这种方式认为对象(实例(总是通过rhs传递给运算符。为了使它工作,我在类外定义了重载运算符。只有当我在头文件(.hpp(中定义它时,它才有效。如果我将函数添加到.cpp文件,为什么编译器会忽略它?。代码片段如下:

//class.hpp
#ifndef POINT_H_
#define POINT_H_
template<class T>
class point{
public:
point(T&x,T&y);
point<T> operator*(T& lambda);
point<T> operator=(const point<T>& P);
void print();
private:
T&x_;
T&y_;
};
#endif
//class.cpp
#include<iostream>
#include "point.hpp"
template<class T>
point<T>::point(T&x,T&y)
:
x_(x),
y_(y)
{
}
template<class T>
point<T> point<T>::operator*(T& lambda){
x_*=lambda;
y_*=lambda;
return *this;
}
template <class T>
point<T> point<T>::operator = (const point<T> & P){
this->x_=P.x_;
this->y_=P.y_;
return *this;
}
template<class T>
void point<T>::print(){
std::cout<<"X is "<<this->x_<<" Y is "<<this->y_<<"n";
}
template class point<int>;
template class point<double>;
template<class T>
point<T> operator*(T& lambda,point<T>& P)
{
return P*lambda;
}

下面显示的最后一个函数只有在我将其添加到头文件中时才有效。

template<class T>
point<T> operator*(T& lambda,point<T>& P)
{
return P*lambda;
}

主文件是

#include<iostream>
#include "point.hpp"
int main(){

double a=3.0;
double b=4.0;
point<double> X = point<double>(a,b);
double m=3.0;
X=m*X;
X.print();
return 0;
}

编译错误为

不匹配"operator*"(操作数类型为"double"one_answers"point"(X=m*X;

如果我在头文件中重载乘法运算符,则重载从双点或双点的两个方向都能正常工作。

C++需要在头中声明一个函数(通常为.h/.hpp(,才能从不同的源文件(.cpp(中使用它

template<class T>
point<T> operator*(T& lambda,point<T>& P);

在您的入口标头(point.hpp(中。

顺便说一句,您对运算符的实现是错误的,因为计算X * m(或m * X(会改变X本身,这通常是不希望的。因此,您应该将操作员*实现为

template<class T>
point<T> point<T>::operator*(T& lambda){
return point<T>(x_*lambda,y_*lambda);
}

或者,您可以将操作员*=定义为

template<class T>
point<T>& point<T>::operator*=(T& lambda){
x_*=lambda;
y_*=lambda;
return *this;
}

X*=m代替X=m*X

相关内容

最新更新