1 Ví dụ về quá tải toán tử Thu Aug 18, 2011 9:12 pm
El Kun
Super Moderator
Ví dụ về quá tải toán tử
- Code:
#include <iostream.h>
#include <conio.h>
#include <math.h>
class PS
{
public:
long tu,mau;
PS()
{
tu=0;
mau=0;
}
~PS(){};
int uscln(long a,long b);
void rutgon();
void nhap();
void xuat();
PS operator+(PS &a);
PS operator-(PS &a);
PS operator*(PS &a);
PS operator/(PS &a);
};
int PS::uscln(long a,long b)
{
if(a!=0 && b!=0)
{
a=abs(a);
b=abs(b);
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
return a;
}
else
return 1;
}
void PS::rutgon()
{
int u;
u=uscln(tu,mau);
tu=tu/u;
mau=mau/u;
}
void PS::nhap()
{
Nhap:
cout<<"Nhap tu so ";
cin>>tu;
cout<<"Nhap mau so ";
cin>>mau;
if(mau==0)
{
cout<<"Mau phai khac 0"<<endl;
goto Nhap;
}
}
void PS::xuat()
{
rutgon();
if(mau<0)
{mau=-mau; tu=-tu;}
if(tu==0)
cout<<"0"<<endl;
else
if(mau==1)
cout<<tu<<endl;
else
cout<<tu<<"/"<<mau<<endl;
}
PS PS::operator+(PS &a)
{
a.tu=tu*a.mau+mau*a.tu;
a.mau=mau*a.mau;
return a;
}
PS PS::operator-(PS &a)
{
a.tu=tu*a.mau-mau*a.tu;
a.mau=mau*a.mau;
return a;
}
PS PS::operator*(PS &a)
{
a.tu=tu*a.tu;
a.mau=mau*a.mau;
return a;
}
PS PS::operator/(PS &a)
{
a.tu=tu*a.mau;
a.mau=mau*a.tu;
return a;
}