// demo1.cpp :
定義控制台應用程式的入口點。
//通過此例程了解重載
#include "stdafx.h"
#include
<iostream>
using namespace std;
class CMath
{
public:
CMath(float
a):m_a(a)
{
}
~CMath()
double Add(double a,double
b);
double Sub(double a,double b);
double Mul(double a,double
double Div(double a,double b);
int Add(int a,int
b)
return a+b;
int Sub(int a,int
return a-b;
int Mul(int a,int
return a*b;
int Div(int a,int
if
(b!=0)
{
return
a/b;
}
return
0;
CMath operator +(CMath&
mymath)
CMath
result(0);
result.m_a=m_a+mymath.m_a;
return result;
CMath
operator -(CMath& mymath)
result.m_a=m_a-mymath.m_a;
operator *(CMath& mymath)
result.m_a=m_a*mymath.m_a;
operator /(CMath& mymath)
(mymath.m_a==0)
mymath.m_a=1;
result.m_a=m_a/mymath.m_a;
operator
++()//前++
this->m_a+=1;
*this;
CMath operator
++(int)//後++,加上參數int,無意義
*t=this;
++(t->m_a);
*t;
--()//前--
this->m_a-=1;
--(int)//後--,加上參數int,無意義
--(this->m_a);
CMath operator +=(CMath &
m_a+=mymath.m_a;
CMath operator -=(CMath &
m_a-=mymath.m_a;
bool operator ==(CMath
&mymath)
(m_a==mymath.m_a);
friend ostream& operator
<<(ostream &os,CMath &t);//必須是友元
friend
iostream& operator >>(iostream &is,CMath
&t);//必須是友元
operator ()(const CMath& t)
CMath(this->m_a=t.m_a);
CMath& operator =(CMath
&t)
this->m_a=t.m_a;
private:
float m_a;
};
ostream&
operator <<(ostream &os,CMath
os<<t.m_a<<endl;
return os;
}
is>>t.m_a;
return
is;
double CMath::Add(double a,double b)
a+b;
double CMath::Sub(double a,double b)
a-b;
double CMath::Mul(double a,double b)
a*b;
double CMath::Div(double a,double b)
if
(b==0)
b=1;
int _tmain(int argc, _TCHAR*
argv[])
mymath(4);
cout<<mymath.Add(1.1,2.1)<<endl;//調用參數為double類型的Add函數
cout<<mymath.Add(1,2)<<endl;//調用參數為int類型的Add函數
cout<<mymath.Sub(1,2)<<endl;//
cout<<mymath.Mul(1,2)<<endl;
cout<<mymath.Div(1.3,2.3)<<endl;
cout<<endl<<endl;
cout<<"mymath:"<<mymath<<endl;
mymath++;
cout<<"mymath++:"<<mymath<<endl;
mymath--;
cout<<"mymath--:"<<mymath<<endl;
cout<<"mymath+mymath:"<<mymath+mymath<<endl;
cout<<"mymath*mymath:"<<mymath*mymath<<endl;
cout<<"mymath/mymath:"<<mymath/mymath<<endl;
mymath1(20);
mymath=mymath1;
cout<<"mymath=mymath1:"<<mymath<<endl;
(mymath==mymath1)
cout<<"mymath==mymath1"<<endl;
mymath1+=mymath;
cout<<"mymath1:"<<mymath1<<endl;
mymath1-=mymath;
mymath1(mymath);
cout<<"mymath1(mymath):"<<mymath1<<endl;