题目:
完善如下代码,实现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; }
|

参考:
#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; }
|
这里还有图片版:
