【发布时间】:2019-01-23 06:03:51
【问题描述】:
我正在研究复数的实现。类Complex 有两个私有成员real_part 和imaginary_part。我想重写乘法运算如下:
template<typename T, typename D>
friend Complex operator * (T lhs, D rhs)
{
double real_a;
double real_b;
double imaginary_a;
double imaginary_b;
if(std::is_same<T, Complex>::value)//if lhs is a Complex
{
real_a = lhs.real_part;
imaginary_a = lhs.imaginary_part;
}
else //base type, some sort of number
{
real_a = lhs;
imaginary_a = 0;
}
if(std::is_same<D, Complex>::value)//if rhs is a Complex
{
real_b = rhs.real_part;
imaginary_b = rhs.imaginary_part;
}
else //base type, some sort of number
{
real_b = rhs;
imaginary_b = 0;
}
Complex result;
result.real_part = (real_b*real_a- imaginary_b*imaginary_a);
result.imaginary_part = (real_b*imaginary_a + imaginary_b*real_a);
return result;
}
我的构造函数看起来像:
Complex::Complex()
{
real_part = 0.0;
imaginary_part = 0.0;
}
和:
Complex(T real, T imaginary)
{
real_part = real;
imaginary_part = imaginary;
}
当我尝试将两个 Complex 相乘时:
Complex a(4.0, 8.0);
Complex b(8, 16);
auto prod = a*b;
auto prod2 = a * 2;
我收到以下错误:
In file included from main.cpp:2:
complex.hpp: In instantiation of ‘Complex operator*(T, D) [with T = Complex; D = Complex]’:
main.cpp:13:17: required from here
complex.hpp:43:16: error: cannot convert ‘Complex’ to ‘double’ in assignment
real_a = lhs;
~~~~~~~^~~~~
complex.hpp:53:16: error: cannot convert ‘Complex’ to ‘double’ in assignment
real_b = rhs;
~~~~~~~^~~~~
complex.hpp: In instantiation of ‘Complex operator*(T, D) [with T = Complex; D = int]’:
main.cpp:14:20: required from here
complex.hpp:43:16: error: cannot convert ‘Complex’ to ‘double’ in assignment
real_a = lhs;
~~~~~~~^~~~~
complex.hpp:48:22: error: request for member ‘real_part’ in ‘rhs’, which is of non-class type ‘int’
real_b = rhs.real_part;
~~~~^~~~~~~~~
complex.hpp:49:27: error: request for member ‘imaginary_part’ in ‘rhs’, which is of non-class type ‘int’
imaginary_b = rhs.imaginary_part;
~~~~^~~~~~~~~~~~~~
我正在尝试以这种方式重载运算符(使用两种泛型类型)以避免有多个重载乘法运算符(即 LHS 是泛型而 RHS 是复杂类型,反之亦然等)。感谢任何帮助,因为我不确定自己做错了什么。
【问题讨论】:
-
也添加您的
Complex构造函数。你使用的是 C++ 的版本? -
嗨@P.W,我已经添加了构造函数。我正在使用 C++11。我意识到我的例子有点欠缺;我希望能够将两个
Complexs 相乘以及例如一个int和一个Complex。 -
我询问版本是因为在 C++17 中,您可以使用
constexpr来消除不正确的分支。在 C++11 中,您必须使用专业化。我想发布一个答案,但有人打败了我。 :)
标签: c++ templates operator-overloading