4-1 复数类的运算符重载
来源:互联网 发布:国家数据平台 编辑:程序博客网 时间:2024/05/29 06:55
Problem Description
通过本题目的练习可以掌握成员运算符重载及友元运算符重载
要求定义一个复数类,重载加法和减法运算符以适应对复数运算的要求,重载插入运算符(<<)以方便输出一个复数的要求。
Input
要求在主函数中创建对象时初始化对象的值。
Output
输出数据共有4行,分别代表a,b的值和它们求和、求差后的值
Example Input
无
Example Output
a=3.2+4.5i
b=8.9+5.6i
a+b=12.1+10.1i
a-b=-5.7-1.1i
#include <iostream>using namespace std;class Complex{private: double real; double imag;public: Complex(double a, double b)//构造函数初始化 { real = a; imag = b; } Complex()//必须有!!!不然定义对象没有默认值时会报错 { real = 0; imag = 0; } friend ostream &operator<<(ostream &output, Complex a)//将<<运算符重载函数定义为友元函数 { output<<a.real; if(a.imag>0) output<<"+"; output<<a.imag<<"i"; return output; } Complex operator +(Complex &a); Complex operator -(Complex &a);};inline Complex Complex::operator+(Complex &a){ Complex c; c.real = real + a.real; c.imag = imag + a.imag; return c;}inline Complex Complex::operator -(Complex &a){ Complex c; c.real = real - a.real; c.imag = imag - a.imag; return c;}int main(){ Complex a(3.2, 4.5), b(8.9, 5.6); cout<<"a="<<a<<endl;//<<运算符重载 cout<<"b="<<b<<endl; cout<<"a+b="<<a + b<<endl;//用到<<和+运算符重载函数 cout<<"a-b="<<a - b<<endl; return 0;}
阅读全文
0 0
- 4-1复数类的运算符重载
- [2677]4-1 复数类的运算符重载
- SDUTOJ 2677 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- sdut 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- SDUTACM 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- 4-1 复数类的运算符重载
- c语言左旋字符串中的k个字符
- Java-出租-pat
- 一些注解知识
- EasyDemo*Animation及其子类体系结构图(on Github)
- CSS中的英文、中文换行与不换行 强制英文换行
- 4-1 复数类的运算符重载
- 2017-11-17 简易的form表单
- 调节SGA后oracle宕机处理
- 表达式的计算结果必须为节点集。
- object Model(对象模型):关于vptr和vtbl
- eclipse无法Debug,Debug 时候ClassNotFoundException的解决方法
- U盘文件被木马隐藏
- 模板方法
- 程序编译-汇编-链接的理解!