4.2运算符重载
来源:互联网 发布:mac用什么杀毒软件 编辑:程序博客网 时间:2024/05/21 07:51
本例为实现复数运算,定义一个复数类,其中私有成员变量有两个,实数部real和虚数部image,通过运算符重载实现复数的直接相加减。
#include<iostream>using namespace std;class Complex { //复数类 private: //定义私有成员变量 double real; //定义实数部 double image; //定义虚数部 public: Complex(void):real(0),image(0) {} //定义参数为空的构造函数 Complex(double rp):real(rp),image(0) {} //定义只有实数部的构造函数 Complex(double rp,double ip):real(rp),image(ip) {} //定义参数同时制定实数和虚数的构造函数 ~Complex() {} //定义析构函数(无特定操作可不写) Complex operator+(const Complex &x) const; //声明重载运算符+ Complex operator-(const Complex &x) const; //声明重载运算符- Complex operator*(const Complex &x) const; //声明重载运算符* Complex operator/(const Complex &x) const; //声明重载运算符/ bool operator==(const Complex &x) const; //声明重载运算符== Complex& operator+=(const Complex &x); //声明重载运算符+= void Print(void) const; //定义类成员输出函数};inline Complex Complex::operator+(const Complex &x) const { //重载运算符的实际函数体 return Complex(real + x.real,image + x.image);}inline Complex Complex::operator-(const Complex &x) const { return Complex(real - x.real,image - x.image);}inline Complex Complex::operator*(const Complex &x) const { return Complex(real * x.real - image * x.image,real * x.image + image * x.real);}Complex Complex::operator/(const Complex &x) const { double m; m = x.real * x.real + x.image * x.image; return Complex((real * x.real + image * x.image) / m, (image * x.real - real * x.image) / m);}inline bool Complex::operator==(const Complex &x) const { //运算符==判断是否相等,应返回bool类型的值 return bool(real == x.real && image == x.image);}Complex& Complex::operator+=(const Complex &x) { //因为+=的结果是将被加数加在自己的成员函数上,所以返回自身的指针 real += x.real; image += x.image; return *this;}void Complex::Print(void) const { //输出函数 cout<<"("<<real<<","<<image<<"i)"<<endl;}int main(void) { //测试函数 Complex a(3, 5), b(2, 3), c; c = a + b * a / b - b; c.Print(); a += b; a.Print(); if(a == c) cout<<"对象a等于对象c"<<endl; else cout<<"对象a不等于对象c"<<endl; return 0;}
0 0
- 4.2运算符重载
- 运算符重载 [++,--,+,<<; &&,||(不可重载)]
- 重载之运算符重载
- 北大 C++ 4.2 赋值运算符重载
- 重载赋值运算符
- C++运算符重载
- 运算符重载
- 运算符重载总结
- 运算符重载例子
- 运算符重载
- 运算符重载
- 基础:运算符重载
- 运算符重载
- 运算符重载
- 重载赋值运算符
- C#运算符重载
- C++-运算符重载
- 重载赋值运算符
- 【Unified Auditing】统一审计的进程架构体系
- C 语言之银行ATM机界面
- Libevent源码学习(四) 事件内部流程解析下部
- 在插入数据库,读写request乱码问题,增加一句话,搞定
- LeetCode -- Remove Element
- 4.2运算符重载
- Notepad++ php格式化 支持php高亮和自动自动函数补全的功能 +安装插件的方法
- 高并发与锁(一)
- Android studio 导入github上的源码库
- LeetCode -- Same Tree
- 天声人語 20151031 10月の言葉から
- 关于手机端浏览器显示兼容
- xcode集成Vungle IOS3.2.0版本视频广告的坑
- 让Mac读写移动硬盘