题目:

完善如下代码,实现complex类,在主程序中调用模板函数max比较两个复数大小(复数大小比较规则是复数实部和虚部的平方和,即realreal+imagimag,平方和大的复数较大)。注意不要修改主程序.

#include <iostream>
using namespace std;
template <typename T>
T Max(T x,T y)
{
return (x>y)?x:y;
}
class complex
{
double real,imag;
public:
};
int main()
{
int i1=2,i2=3;
cout<<"Max of i1 and i2 is <<Max(i1,i2)<<endl;
complex a1(2,3),a2(1,2),a3;
cout<<"a1=";
a1.print();
cout<<"a2=";
a2.print();
a3=Max(a1,a2);
cout<<"Max of complex a1 and a2 is ";
a3.print();
return 0;
}

image-20210508110054861

参考:

#include <iostream>
using namespace std;
template<typename T>
T Max(T x, T y) {
return (x > y ? x : y);
}
class complex {
double m_real, m_imag;
public:
complex(double); //构造函数,用于比较复数和实数
complex(double, double); //构造函数,用于构造一般的函数
void print(void); //打印输出
bool operator>(const complex& t); //重载`>`,用于比较复数大小

};
complex::complex(double real = 0) :m_real(real), m_imag(0) {}
complex::complex(double real, double imag) : m_real(real), m_imag(imag) {}
void complex::print() {
cout << " " << m_real << "+" << m_imag << "i \n";
}
bool complex::operator>(const complex& t) {
if ((this->m_imag * this->m_imag + this->m_real * this->m_real) > (t.m_imag * t.m_imag + t.m_real * t.m_real))
return true;
else return false;
}
int main(void) {
int i1 = 2, i2 = 3;
cout << "Max of i1 and i2 is" << Max(i1, i2) << endl;

complex a1(2, 3), a2(1, 2), a3;
cout << "a1=";
a1.print();
cout << "a2=";
a2.print();
a3 = Max(a1, a2);
cout << "Max of complex a1 and a2 is";
a3.print();
return 0;
}

这里还有图片版:

code