我有一个Complex类,带有定义的+,-,*,/的Friend Complex运算符。
class Complex
{
private:
float Re;
float Im;
public:
friend Complex operator + (const Complex ,const Complex );
friend Complex operator * (const Complex ,const Complex );
friend Complex operator - (const Complex ,const Complex );
friend Complex operator / (const Complex ,const Complex );
};
Complex operator + (const Complex a,const Complex b)
{
Complex c(0,0);
c.Re=a.Re+b.Re;
c.Im=a.Im+b.Im;
return c;
}
Complex operator * (const Complex a,const Complex b)
{
Complex c(0,0);
c.Re=a.Re*b.Re;
c.Im=a.Im*b.Im;
return c;
}
Complex operator - (const Complex a,const Complex b)
{
Complex c(0,0);
c.Re=a.Re-b.Re;
c.Im=a.Im-b.Im;
return c;
}
Complex operator / (const Complex a,const Complex b)
{
if(b.Im && b.Re)
{
Complex c(0,0);
c.Re=a.Re/b.Re;
c.Im=a.Im/b.Im;
return c;
}
else
{
std::cout<<"Cannot divide, one of parametars is zero."<<std::endl;
}
}
我想优化的是,而不是多次编写所有代码,而只需更改+,-,*,/运算符,就可以编写一次,而在int main()中 某些操作符被称为(使用),只是读取它并将其应用于函数。有可能吗?
答案 0 :(得分:0)
您可以执行以下操作:
将此模板函数添加到Complex
中:
template <typename OP>
static Complex apply(const Complex a, const Complex b, OP op) {
Complex c;
c.Re = op(a.Re, b.Re);
c.Im = op(a.Im, b.Im);
return c;
}
然后,运算符的实现要小一些:
Complex operator + (const Complex a,const Complex b)
{
return Complex::apply(a, b, std::plus<float>());
}
Complex operator * (const Complex a,const Complex b)
{
return Complex::apply(a, b, std::multiplies<float>());
}
Complex operator - (const Complex a,const Complex b)
{
return Complex::apply(a, b, std::minus<float>());
}
Complex operator / (const Complex a,const Complex b)
{
if(b.Im && b.Re)
{
return Complex::apply(a, b, std::divides<float>());
}
else
{
std::cout<<"Cannot divide, one of parametars is zero."<<std::endl;
// Note: missing return value here
}
}
注意:对于复数,乘法和除法的定义不是这样。
注2:我不认为这会小很多,因为据我所知,您必须一个一个地定义运算符(立即定义它们并不容易,至少在C ++ 17中不是这样) )。