首页 > 其他 > 详细

运算符的重载

时间:2016-02-19 14:31:43      阅读:231      评论:0      收藏:0      [点我收藏+]

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>

using namespace std;


class Complex

{

public:

Complex(double _real, double _image);    //构造函数

Complex(const Complex & p);           //拷贝构造函数

Complex operator+(const Complex &);      //加法运算符的重载

Complex operator-(const Complex &);      //减法运算符的重载

Complex operator*(const Complex &);      //乘法运算符的重载

Complex operator/(const Complex &);      //除法运算符的重载

void ShowNumber();                  //输出函数

~Complex();                       //析构函数

private:

double real;

double image;

};


Complex::Complex(double _real, double _image)    //构造函数

{

real = _real;

image = _image;

}


Complex::Complex(const Complex & p)      //拷贝构造函数

{

real = p.real;

image = p.image;

}


Complex::~Complex()         //析构函数

{

cout << "已调用析构函数" << endl;

}


Complex Complex::operator + (const Complex &op1)     //加法运算符的重载

{

return Complex(real + op1.real, image + op1.image);

}


Complex Complex::operator-(const Complex &op1)   //减法运算符的重载

{

return Complex(real - op1.real, image + op1.image);

}


Complex Complex::operator*(const Complex &op1)    //乘法运算符的重载

{

return Complex((real * op1.real) - (image * op1.image), (real * op1.image) + (op1.real * image));

}


void Complex::ShowNumber()      //输出函数

{

cout << real << "+" << image << "i" << endl;

}


int main()

{

system("color e");

Complex op1(1.0, 2.0), op2(3.0, 4.0), op3(5.0, 6.0);

Complex op4(op3);


op1.ShowNumber();

op2.ShowNumber();

op3.ShowNumber();

op4.ShowNumber();


op1 = op2 + op3;

op2 = op3 - op4;

op3 = op3*op4;


op1.ShowNumber();

op2.ShowNumber();

op3.ShowNumber();


system("pause");

return 0;

}


运行结果如下:

技术分享


本文出自 “零点时光” 博客,请务必保留此出处http://10741764.blog.51cto.com/10731764/1743317

运算符的重载

原文:http://10741764.blog.51cto.com/10731764/1743317

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!