我是靠谱客的博主 激动绿草,这篇文章主要介绍输出运算符重载,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* * 程序的版权和版本声明部分: * Copyright (c) 2013, 烟台大学计算机学院 * All rights reserved. * 文件名称:test.cpp * 作 者:任子仪 * 完成日期:2014年 4月 22日 * 版 本 号:v12.1 * 输入描述:无 * 问题描述:。 * 程序输出: * 问题分析:略 * 算法设计:略 */ #include<iostream> using namespace std; class Complex { public: Complex() { real=0; imag=0; } Complex(double r,double i) { real=r; imag=i; } //二目运算符重载 Complex operator+(Complex &c2); Complex operator-(Complex &c2); Complex operator*(Complex &c2); Complex operator/(Complex &c2); //一目运算符重载 Complex operator-(); friend ostream& operator << (ostream&,Complex&); private: double real; double imag; }; ostream& operator << (ostream& output,Complex& c) { if(c.imag>0) output<<c.real<<"+"<<c.imag<<"i"<<endl; else output<<c.real<<c.imag<<"i"<<endl; return output; } //下面定义成员函数 Complex Complex::operator+(Complex &c2) { return Complex(real+c2.real,imag+c2.imag); } Complex Complex::operator-(Complex &c2) { return Complex(real-c2.real,imag-c2.imag); } Complex Complex::operator*(Complex &c2) { Complex c; c.real=real*c2.real-imag*c2.imag; c.imag=real*c2.imag+imag*c2.real; return c; } Complex Complex::operator/(Complex &c2) { Complex c; double d=c2.real*c2.real+c2.imag*c2.imag; c.real=(real*c2.real+imag*c2.imag)/d; c.imag=(imag*c2.real-real*c2.imag)/d; return c; } Complex Complex::operator-() { Complex c; c.imag=0-imag; c.real=0-real; return c; } //下面定义用于测试的main()函数 int main() { Complex c1(3,4),c2(5,-10),c3; cout<<"c1="<<c1; cout<<"c2="<<c2; c3=c1+c2; cout<<"c1+c2="<<c3; c3=c1-c2; cout<<"c1-c2="<<c3; c3=c1*c2; cout<<"c1*c2="<<c3; c3=c1/c2; cout<<"c1/c2="<<c3; c3=-c1; cout<<"-c1="<<c3; return 0; }

示例图片:




心得体会:上课时怎么都不明白为什么可以直接输出结果还有重载,现在明白了。实践

出的,高兴啊。。。

最后

以上就是激动绿草最近收集整理的关于输出运算符重载的全部内容,更多相关输出运算符重载内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部