C++复数运算 重载
C++复数运算 重载
近期整理下很久前写的C++程序,这里就把它放在此文中了,有些比较简单,但是很有学习价值。
下面就是自己很久前实现的复数重载代码,这里没有考虑特殊情况,像除法中,分母不为零情况。
#include <iostream>
/*
#include <conio.h>
#include<stdio.h>
#include<iomanip>
#include<string>
#include<sstream>
*/
using namespace std;
class complex
{
double real,imag;
public:
complex(double,double);
void disp(char *);
friend complex operator + (complex,complex);
friend complex operator - (complex,complex);
friend complex operator * (complex,complex);
friend complex operator / (complex,complex);
};
complex::complex (double r=0,double i=0)
{
real = r;
imag = i;
}
void complex::disp (char *str)
{
cout.unsetf(ios::showpos);
cout<<str<<"="<<real;
if (imag)
{
cout.setf(ios::showpos);
cout<<imag<<'i';
}
cout<<endl;
cout.unsetf(ios::showpos);
}
complex operator + (complex cpl1,complex cpl2)
{
double t=cpl1.real+cpl2.real;
double i=cpl1.imag+cpl2.imag;
return complex(t,i);
}
complex operator - (complex cpl1,complex cpl2)
{
double t=cpl1.real-cpl2.real;
double i=cpl1.imag-cpl2.imag;
return complex(t,i);
}
complex operator * (complex cpl1,complex cpl2)
{
double t=cpl1.real*cpl2.real - cpl1.imag*cpl2.imag;
double i=cpl1.real*cpl2.imag + cpl1.imag*cpl2.real;
return complex(t,i);
}
complex operator / (complex cpl1,complex cpl2)
{
double t=(cpl1.real*cpl2.real+cpl1.imag*cpl2.imag)/(cpl2.real*cpl2.real+cpl2.imag*cpl2.imag);
double i=(cpl1.imag*cpl2.real-cpl1.real*cpl2.imag)/(cpl2.real*cpl2.real+cpl2.imag*cpl2.imag);
return complex(t,i);
}
int main(void)
{
complex c1(25,40),c2(100,200),c3(0);
c1.disp("c1");
c2.disp("c2");
c3=c1+c2;
c3.disp("c3");
c3=c1-c3;
c3.disp("c3");
c3=c1*c2;
c3.disp("c3");
c3=c1/c2;
c3.disp("c3");
getchar();
return 0;
}
《C++ 设计新思维》 下载见
C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码
读C++ Primer 之构造函数陷阱
读C++ Primer 之智能指针
读C++ Primer 之句柄类
将C语言梳理一下,分布在以下10个章节中:
- Linux-C成长之路(一):Linux下C编程概要
- Linux-C成长之路(二):基本数据类型
- Linux-C成长之路(三):基本IO函数操作
- Linux-C成长之路(四):运算符
- Linux-C成长之路(五):控制流
- Linux-C成长之路(六):函数要义
- Linux-C成长之路(七):数组与指针
- Linux-C成长之路(八):存储类,动态内存
- Linux-C成长之路(九):复合数据类型
- Linux-C成长之路(十):其他高级议题
本文永久更新链接地址:
评论暂时关闭