在之前所做复数类的基础上,实现:
1)为该复数类重载*运算符,以友元的形式重载;
2)为该复数类重载赋值运算,可接收的字符串如:3+5i , -3+2i , 7-8i
/*
2.在复数类的基础上,实现:
1)为该复数类重载*运算符,以友元的形式重载;
2)为该复数类重载赋值运算,可接收的字符串如:3+5i , -3+2i , 7-8i
*/
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;
class Complex
{
double real;
double image;
public:
Complex(double r = 0, double i = 0);
Complex(const Complex& other);
void print();
Complex operator + (const Complex& other);
Complex operator - (const Complex& other); //减法, 二元
Complex operator - (); //求负,一元
Complex operator = (const Complex& other); //赋值, 二元
friend Complex operator* (const Complex &a,const Complex &b);//重载*
Complex operator = (string s); //赋值,接收的字符串
};
Complex::Complex(double r, double i)
{
real = r;
image = i;
}
Complex::Complex(const Complex& other)
{ //此拷贝构造函数与缺省拷贝函数相同,可以省略。
real = other.real;
image = other.image;
}
void Complex::print()
{
cout << real;
if(image > 0)
cout << "+" << image << "i";
else if (image < 0)
cout << image << "i";
cout << "\n";
}
Complex Complex:: operator + (const Complex& other)
{
Complex temp;
temp.real = real + other.real; //相当于temp.real=this->real+other.real;
temp.image = image + other.image;
return temp;
}
Complex Complex:: operator - (const Complex& other)
{
Complex temp;
temp.real = real - other.real;
temp.image = image - other.image;
return temp;
}
Complex Complex:: operator - ()
{
Complex temp;
temp.real = -real;
temp.image = -image;
return temp;
}
Complex Complex:: operator = (const Complex& other)
{ //此赋值运算符的重载与缺省赋值运算相同,可以省略。
real = other.real;
image = other.image;
return *this;
}
Complex operator*(const Complex &a, const Complex &b)//重载*
{
Complex tmp;
tmp.real = a.real * b.real - a.image * b.image;
tmp.image = a.real * b.image + a.image * b.real;
return tmp;
}
Complex Complex::operator = (string s) //赋值,接收的字符串
{
int i,n=-1;
string temp;
if (s.find('i')== s.npos)//如果没有虚部
{
image = 0;
real=stoi(s);
}
else
{
temp.push_back(s[0]);
if (s.find('+') != s.npos)
n = s.find('+');
else if(s.find('-') != s.npos)
n= s.find('-');
else
{
real = 0;
n = -1;
}
if (n != -1)
{
for (i = 1; i < n; i++)
{
temp.push_back(s[i]);
}
real = stoi(temp);
}
temp.clear();
for (;i<s.rfind('i'); i++)
{
if(s[i]!='+'&& s[i] != '-')
temp.push_back(s[i]);
else if (s[i] == '-')
temp.push_back(s[i]);
else if (s[i] == '+')
continue;
}
image = stoi(temp);
}
return *this;
}
int main()
{
Complex c1(1, 2);
Complex c2(2, 3);
Complex c3(c1);
cout << "c1:";
c1.print();
cout << "c2:";
c2.print();
c3 = c1 * c2;
cout << "c3=c1*c2:";
c3.print();
string s = "3+5i";
c3 = s;
cout << "c3=3+5i:";
c3.print();
s = "-3+2i";
c3 = s;
cout << "c3=-3+2i:";
c3.print();
s = "7-8i";
c3 = s;
cout << "c3=7-8i:";
c3.print();
system("PAUSE");
return 0;
}