近期整理下很久前寫的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++ 設計新思維》 下載見 http://www.linuxidc.com/Linux/2014-07/104850.htm
C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm
讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm
讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm
讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm
將C語言梳理一下,分布在以下10個章節中: