第七周实验报告3

实验目的:课本P314的例10.1实现了一个复数类,但是美中不足的是,复数类的实部和虚部都固定只能是double型的,可以通过模板类的技术手段,设计Complex,使实部和虚部的类型为定义对象时用的实际类型

实验要求:1.类成员函数在类外定义 2.在此基础上,在实现减法、乘法和除法。

实验代码:

#include <iostream>

#include <cmath>

using namespace std;

template <class numtype> //声明一个类模板,虚拟类型为numtype

class Complex //定义Complex类
{
public:
	Complex(){real = 0; imag = 0;} //定义构造函数
	Complex(numtype r, numtype i){real = r; imag = i;} //构造函数重载
	Complex complex_add(Complex &c2); //声明复数相加的函数
    Complex complex_cut(Complex &c2); //声明复数相减的函数
    Complex complex_multiplication(Complex &c2); //声明复数相乘的函数
    Complex complex_division(Complex &c2); //声明复数相除的函数
	void display();
private:
	numtype real; //实部
	numtype imag; //虚部
};

template <class numtype> 
Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> &c2) //定义复数相加的函数
{
	Complex<numtype> c;
	c.real = real + c2.real; //两个复数的实部相加
	c.imag = imag + c2.imag; //两个复数的虚部相加
	return c;
}

template <class numtype> 
Complex<numtype> Complex<numtype>::complex_cut(Complex<numtype> &c2) //定义复数相减的函数
{
	Complex<numtype> c;
	c.real = real - c2.real; //两个复数的实部相减
	c.imag = imag - c2.imag; //两个复数的虚部相减
	return c;
}

template <class numtype> 
Complex<numtype> Complex<numtype>::complex_multiplication(Complex<numtype> &c2) //定义复数相乘的函数
{
	Complex<numtype> c;
	c.real = (real * c2.real) - (imag * c2.imag); 
	c.imag = (imag * c2.real) + (real * c2.imag);
	return c;
}

template <class numtype> 
Complex<numtype> Complex<numtype>::complex_division(Complex<numtype> &c2) //定义复数相除的函数
{
	Complex<numtype> c;
	c.real = ((real * c2.real) + (imag * c2.imag)) / (pow(c2.real, 2) + pow(c2.imag, 2)); 
	c.imag = ((imag * c2.real) - (real * c2.imag)) / (pow(c2.real, 2) + pow(c2.imag, 2));
	return c;
}

template <class numtype>
void Complex<numtype>::display()  //定义输出函数
{
	cout << "(" << real << ", " << imag << "i)" << endl;
}

int main( )
{	
	Complex<int> c1(3, 4), c2(5, -10), c3, c7;  
	c3 = c1.complex_add(c2);
	cout << "c1 + c2 = "; 
	c3.display();
	
	Complex<double> c4(3.1, 4.4), c5(5.34, -10.21), c6, c8, c9;  
	c6 = c4.complex_add(c5);
	cout << "c4 + c5 = "; 
	c6.display(); 

	c7 = c1.complex_cut(c2);
	cout << "c1 - c2 = ";
	c7.display();
	c8 = c4.complex_multiplication(c5);
	cout << "c4 * c5 = ";
	c8.display();
	c9 = c4.complex_division(c5);
	cout << "c4 / c5 = ";
	c9.display();
	system("pause");
	return 0;
}

实验结果截图:

第七周实验报告3_第1张图片

实验心得:

实验中又运用了新知识——模板类,让我深刻晓得了什么叫欲速则不达,结果只有一个,大堆大堆的error,看得人心慌啊!所以,做题之前还是仔仔细细的看好课本吧,就这次的模板类来说,没看好课本就急于编写代码的我啊,可是受够了教训。其实要点就一个,搞清楚运用模板类的格式,问题就能很好的迎刃而解。

还有老师也真是够“讨厌”的,干嘛难为人啊,还要实现复数的乘法和除法,这个谁会啊,还要上网查计算方法,这才发现渐渐老去的自己,和渐行渐远的高中知识啊!!!!

你可能感兴趣的:(c,System,Class)