这个要用到运算符重载,网上搜索关键词 “C++ operator”即可找到答案。
参考:
#include <iostream>
using namespace std;
class CComplex {
double a;
double b;
public:
CComplex() {
this->a = 0;
this->b = 0;
};
CComplex(double a, double b);
CComplex operator+(const CComplex &A) const;
CComplex operator-(const CComplex &A) const;
friend istream & operator>> (istream &in, CComplex &c);
friend ostream & operator<< (ostream &ou, const CComplex &c);
};
CComplex::CComplex(double a, double b) {
this->a = a;
this->b = b;
}
CComplex CComplex::operator+(const CComplex &A) const {
CComplex c;
c.a = this->a + A.a;
c.b = this->b + A.b;
return c;
}
CComplex CComplex::operator-(const CComplex &A) const {
CComplex c;
c.a = this->a - A.a;
c.b = this->b - A.b;
return c;
}
istream &operator>>(istream &in, CComplex &c) {
in >> c.a >> c.b;
return in;
}
ostream &operator<<(ostream &ou, const CComplex &c) {
ou << noshowpos << c.a << showpos << c.b << "i" << endl;
return ou;
}
如有用请采纳
#include<string>
#include<iostream>
using namespace std;
struct fushu
{
int INT;
int VOID;
};
void AddFunc(fushu a, fushu b)
{
int m_INT;
int m_VOID;
m_INT = a.INT + b.INT;
m_VOID = a.VOID + b.VOID;
cout << "两个复数的和是:" << m_INT << "+" << m_VOID << "i" << endl;
}
void MinusFunc(fushu a, fushu b)
{
int m_INT;
int m_VOID;
m_INT = a.INT - b.INT;
m_VOID = a.VOID - b.VOID;
if (m_VOID<0){
cout << "两个复数的差是:" << m_INT << m_VOID << "i" << endl;
}
else{
cout << "两个复数的差是:" << m_INT << "+" << m_VOID << "i" << endl;
}
}
int main()
{
fushu a;
fushu b;
cout << "请分别输入第一个复数的实部和虚部:" << endl;
cin >> a.INT >> a.VOID;
cout << "请分别输入第二个复数的实部和虚部:" << endl;
cin >> b.INT >> b.VOID;
cout << "第一个复数是:" << a.INT << "+" << a.VOID << "i" << endl;
cout << "第二个复数是:" << b.INT << "+" << b.VOID << "i" << endl;
AddFunc(a,b);
MinusFunc(a,b);
return 0;
}
基本可以了,可以直接运行
记得控制台输入四个数
```c++
#include<iostream>
#include<string>
using namespace std;
class CComplex {
private:
double real;
double image;
public:
CComplex(double r = 0.0, double i = 0.0);
friend ostream & operator<< (ostream &ou, const CComplex &c);
CComplex operator+ (CComplex c);
CComplex operator- (CComplex c);
};
ostream &operator<< (ostream &ou, const CComplex &c) {
if (c.image >= 0)
return ou << c.real << "+" << c.image << "i" << endl;
else
return ou << c.real << c.image << "i" << endl;
}
CComplex::CComplex(double r,double i) {
real = r;
image = i;
}
CComplex CComplex::operator+ (CComplex c) {
CComplex temp;
temp.real = real + c.real;
temp.image = image + c.image;
return temp;
}
CComplex CComplex::operator- (CComplex c) {
CComplex temp;
temp.real = real - c.real;
temp.image = image - c.image;
return temp;
}
int main() {
double r1, r2, i1, i2;
cin>>r1>>i1;
cin>>r2>>i2;
CComplex c1(r1, i1), c2(r2, i2), c3, c4;
cout<<c1;
cout<<c2;
c3 = c1 + c2;
cout<<c3;
c4 = c1 - c2;
cout<<c4;
return 0;
}
```