-2

我想重载 * 运算符,以便它将类的复杂子变量相乘并返回复杂结果。我的想法如下:

#include <complex>

using namespace std; 

class a{
public:
  std::complex<double> x0;
...
};

template<class T> complex<T>  operator*(const a &lfv, const a &rfv){
  return lfv.x0*rfv.x0;
}

但它不起作用......有什么想法或评论吗?

4

3 回答 3

3

Your class holds std::complex<double> data members and is not a template. You need a non-template function:

std::complex<double> operator*(const a& lfv, const a& rfv){
  return lfv.x0*rfv.x0;
}

In your example, there is no way for your template function to deduce the return type from the arguments passed to it.

于 2013-04-11T14:12:40.963 回答
1

复杂类已经解决了这个问题,即它总是在乘法后返回复杂的结果。

用法如下:

complex<double> p(10,20);
complex<double> q(2,3);
std::cout << p*q << endl;

输出是:

(-40,70)

或者,如果您可以这样做:

class a{
public:
  std::complex<double> x0;
};

complex<double>  operator*(const a &lfv, const a &rfv){
  return lfv.x0*rfv.x0;
}

int main()
{
    a  y;
    y.x0 = complex<double>(10,20);
    a  z;
    z.x0 = complex<double>(10,20);
    std::cout << y*z << endl;
}
于 2013-04-11T15:13:18.517 回答
0

我想不出一种方法来做你正在寻找的东西(返回 a complex<T>from operator*),因为operator*不能自动扣除类型,所以你必须指定类型,如下例所示:

a my_var1;
a my_var2;
complex<double> result = operator*<double>(my_var1, my_var2);

...或者您可以遵循@juanchopanza 的建议,不要使用带有operator*.

于 2013-04-11T14:23:53.313 回答