一、完成复数类CComplex的定义,(包括real和image两个double型数据成员)
●包括构造函数,print()打印数据成员值的成员函数.
● 并用成员函数重载 ‘=’赋值运算符和前、后‘++’运算符,用友元函数重载双目‘+’和‘-’运算符.
二、在主函数中分别进行以下测试 :
●对象=对象+对象;
●对象=对象-对象;
●++对象;
并分别调用print函数打印对象数据成员值
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class CComplex
{
private:
double real, image;
public:
CComplex(double r = 0, double i = 0) { real = r; image = i; }
~CComplex() {}
//友元函数+
friend CComplex& operator +(CComplex& c1, CComplex& c2)
{
CComplex t;
t.real = c1.real + c2.real;
t.image= c1.image + c2.image;
return t;
}
friend CComplex& operator -(CComplex& c1, CComplex& c2)
{
CComplex t;
t.real = c1.real - c2.real;
t.image = c1.image - c2.image;
return t;
}
//成员函数=
CComplex& operator =(CComplex& c)
{
CComplex t;
t.real = c.image;
t.image = c.image;
}
//前置++
CComplex operator ++() {
this->real += 1;
this->image += 1;
return *this;
}
//后置++
CComplex operator ++(int) {
CComplex c(this->real, this->image);
this->real += 1;
this->image += 1;
return c;
}
//前置--
CComplex operator --() {
this->real -= 1;
this->image -= 1;
return *this;
}
//后置--
CComplex operator --(int) {
CComplex c(this->real, this->image);
this->real -= 1;
this->image -= 1;
return c;
}
void print()
{
if (image > 0)
cout << real << "+" << image << "i";
else if (image == 0)
cout << real;
else
cout << real << image << "i";
}
};
int main()
{
CComplex a(3, 5), b(5, 3);
cout << "a: ";
a.print();
cout << endl << "b: ";
b.print();
cout << endl << "a+b= ";
CComplex c = a + b;
c.print();
cout << endl << "a-b= ";
CComplex d = a - b;
d.print();
cout << endl << "++a : ";
++a;
a.print();
return 0;
}
#include<iostream>
using namespace std;
class CComplex
{
public:
//CComplex() CComplex(20) CComplex(30,30)
CComplex(int r = 0, int i = 0)//构造
:mreal(r), mimage(i) {}
CComplex operator=(CComplex &c2)
{
CComplex tmp;
tmp.mreal = c2.mreal ;
tmp.mimage = c2.mimage ;
return tmp;
}
//加法运算符重载
friend CComplex operator+(CComplex c1,CComplex c2)
{
return CComplex(c1.mreal+c2.mreal,c1.mimage+c2.mimage);
}
friend CComplex operator-(CComplex c1,CComplex c2)
{
return CComplex(c1.mreal-c2.mreal,c1.mimage-c2.mimage);
}
CComplex operator++(int)//后置++重载
{
return CComplex(mreal++, mimage++);
}
CComplex& operator++()//前置++重载
{
mreal += 1;
mimage += 1;
return *this;//返回加完后的值
}
void show()
{
cout << "real:" << mreal << " image:" << mimage << endl;
}
private:
double mreal;//实部
double mimage;//虚部
};
int main()
{
CComplex comp1(20, 20);
CComplex comp2(10, 10);
CComplex comp3 = comp1 + comp2;
comp3.show();
CComplex comp4 = comp1 - comp2;
comp4.show();
comp4++;
comp4.show();
return 0;
}