定义虚数类并且运用运算符重载实现虚实相加

这两天学会了继承、基类、派生类、多态、抽象类等等的定义,了解了构造函数和析构函数,接下来会写几个这方面的实例。此外,学了一些html和javascript的基础知识为学习XML做准备(虽然我不知道这和java有什么关系,但是能做项目事好的
(逃

代码如下:

#include
using namespace std;

class Complex {
private:
	double real, imag;
public:
	Complex(double r=0,double i=0):real(r),imag(i){}//构造函数
	double Real() { return real; }
	double Imag() { return imag; }
	Complex operator +(Complex&);
	Complex operator +(double);
	bool operator ==(Complex);//重载运算符
	~Complex() {};//析构函数
};
Complex Complex::operator +(Complex& c) {
	Complex temp;
	temp.real = real + c.real;
	temp.imag = imag + c.imag;
	return temp;
}
Complex Complex::operator+(double d) {
	Complex temp;
	temp.real = real + d;
	temp.imag = imag;
	return temp;
}
bool Complex::operator == (Complex c) {
	if (real == c.real && imag == c.imag)
		return true;
	else
		return false;//用于比较虚数是否相等,需要就在主函数加上吧
}
int main() {
	double a, b, c, d;
	cout << "请输入相加两数的实部和虚部:"<> a >> b >> c >> d;
	Complex c1(a, b), c2(c, d);
	Complex  c3 = c1 + c2;
	cout << "您输入两个数相加的结果是:" << c3.Real() << "+j" << c3.Imag();





}

你可能感兴趣的:(c/c++)