Skip to content

Commit 9262ebf

Browse files
author
lanyuanxiaoyao
committed
修改文件: _posts/2015-10-31-operator.md
1 parent cb0c4ae commit 9262ebf

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

_posts/2015-10-31-operator.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
layout: post
3+
title: C++ 运算符重载
4+
date: 2015-10-31 10:50
5+
categories: C++
6+
tags: [C++]
7+
---
8+
本例为实现复数运算,定义一个复数类,其中私有成员变量有两个,实数部real和虚数部image,通过运算符重载实现复数的直接相加减。
9+
```cpp
10+
#include<iostream>
11+
using namespace std;
12+
class Complex { //复数类
13+
private: //定义私有成员变量
14+
double real; //定义实数部
15+
double image; //定义虚数部
16+
public:
17+
Complex(void):real(0),image(0) {} //定义参数为空的构造函数
18+
Complex(double rp):real(rp),image(0) {} //定义只有实数部的构造函数
19+
Complex(double rp,double ip):real(rp),image(ip) {} //定义参数同时制定实数和虚数的构造函数
20+
~Complex() {} //定义析构函数(无特定操作可不写)
21+
22+
Complex operator+(const Complex &x) const; //声明重载运算符+
23+
Complex operator-(const Complex &x) const; //声明重载运算符-
24+
Complex operator*(const Complex &x) const; //声明重载运算符*
25+
Complex operator/(const Complex &x) const; //声明重载运算符/
26+
bool operator==(const Complex &x) const; //声明重载运算符==
27+
Complex& operator+=(const Complex &x); //声明重载运算符+=
28+
void Print(void) const; //定义类成员输出函数
29+
};
30+
inline Complex Complex::operator+(const Complex &x) const { //重载运算符的实际函数体
31+
return Complex(real + x.real,image + x.image);
32+
}
33+
inline Complex Complex::operator-(const Complex &x) const {
34+
return Complex(real - x.real,image - x.image);
35+
}
36+
inline Complex Complex::operator*(const Complex &x) const {
37+
return Complex(real * x.real - image * x.image,real * x.image + image * x.real);
38+
}
39+
Complex Complex::operator/(const Complex &x) const {
40+
double m;
41+
m = x.real * x.real + x.image * x.image;
42+
return Complex((real * x.real + image * x.image) / m, (image * x.real - real * x.image) / m);
43+
}
44+
inline bool Complex::operator==(const Complex &x) const { //运算符==判断是否相等,应返回bool类型的值
45+
return bool(real == x.real && image == x.image);
46+
}
47+
Complex& Complex::operator+=(const Complex &x) { //因为+=的结果是将被加数加在自己的成员函数上,所以返回自身的指针
48+
real += x.real;
49+
image += x.image;
50+
return *this;
51+
}
52+
void Complex::Print(void) const { //输出函数
53+
cout<<"("<<real<<","<<image<<"i)"<<endl;
54+
}
55+
56+
int main(void) { //测试函数
57+
Complex a(3, 5), b(2, 3), c;
58+
c = a + b * a / b - b;
59+
c.Print();
60+
61+
a += b;
62+
a.Print();
63+
64+
if(a == c) cout<<"对象a等于对象c"<<endl;
65+
else cout<<"对象a不等于对象c"<<endl;
66+
67+
return 0;
68+
}
69+
```

0 commit comments

Comments
 (0)