复数由实部和虚部组成 复数间的运算通过实部和虚部,我们构建一个复数类来模拟复数间的操作
类定义如下:
-
//复数的运算
-
class Complex {
-
private:
-
int real; //复数的实部
-
int image; //复数的虚部
-
public:
-
-
void myPrint() {
-
cout << this->real << " " << this->image << "i" << endl; //显示复数
-
}
-
-
Complex( int real= 0, int image= 0) { //构造函数
-
this->real = real;
-
this->image = image;
-
}
现在我们通过操作符的重载来实现复数间的直接运算
加号的重载:
-
//重载加号
-
Complex operator+( const Complex &obj) {
-
Complex res;
-
res.real = this->real + obj.real;
-
res.image = this->image + obj.image;
-
return res;
-
}
重载的重要信息:
1)为了能实现操作符重载,至少得有一个对象是用户自定义的对象,如上述加号重载是基于Complex类对象
2)赋值操作符: 编译器会自动的给每个类创建一个默认的赋值操作符。它会将所有成员从右边赋给左边,大多数情况下可以正常工作(不正常的地方与拷贝构造一样)。
全局运算符重载函数:
运算符函数与普通函数一样。唯一的不同在于,运算符函数的名字通常由operator关键字加上运算操作符组成。
我们可以把操作符函数定义为全局的
-
Complex operator * ( const Complex &obj1, const Complex &obj2) {
-
Complex res;
-
res.real = obj1.real * obj2.real;
-
res.image = obj1.image * obj2.image;
-
return res;
-
}
friend Complex operator * (const Complex &obj1, const Complex &obj2);
这样不但实现了全局函数,还可以传入两个形参
类型转换的重载:
我们可以自定义类型转换操作符,把一个类型转换成另一个类型
-
operator float() const {
-
return float( this->real) / float( this->image);
-
}
使用:
-
float val = C;
-
-
cout << val << endl;
整个程序如下:
-
-
using namespace std;
-
-
-
//复数的运算
-
class Complex {
-
private:
-
int real; //复数的实部
-
int image; //复数的虚部
-
public:
-
-
void myPrint() {
-
cout << this->real << " " << this->image << "i" << endl; //显示复数
-
}
-
-
Complex( int real= 0, int image= 0) { //构造函数
-
this->real = real;
-
this->image = image;
-
}
-
-
//重载加号
-
Complex operator+( const Complex &obj) {
-
Complex res;
-
res.real = this->real + obj.real;
-
res.image = this->image + obj.image;
-
return res;
-
}
-
-
-
//重载减号
-
Complex operator-( const Complex &obj) {
-
Complex res;
-
res.real = this->real - obj.real > 0 ? this->real - obj.real : 0;
-
res.image = this->image - obj.image > 0 ? this->image - obj.image : 0;
-
return res;
-
}
-
-
//重载乘号
-
//使全局函数可以使用私有的类
-
friend Complex operator * ( const Complex &obj1, const Complex &obj2);
-
-
operator float() const {
-
return float( this->real) / float( this->image);
-
}
-
-
-
};
-
-
-
//全局的乘号重载
-
Complex operator * ( const Complex &obj1, const Complex &obj2) {
-
Complex res;
-
res.real = obj1.real * obj2.real;
-
res.image = obj1.image * obj2.image;
-
return res;
-
}
-
-
-
-
int main() {
-
-
Complex A(10, 20);
-
Complex B(20, 30);
-
-
A.myPrint();
-
cout << endl << endl;
-
B.myPrint();
-
cout << endl << endl;
-
-
Complex C = A + B; //重载的加号
-
C.myPrint();
-
-
C = B - A; //重载的减号
-
C.myPrint();
-
-
C = B * A; //重载的乘号
-
C.myPrint();
-
-
float val = C;
-
-
cout << val << endl;
-
-
system( "PAUSE");
-
return 0;
-
}
-