phần nạp chồng các toán tử:
phần main:
Bài làm tham khảo:
- Code:
ostream& operator<<(ostream& out,const SOPHUC &s)
{
out<<s.thuc<<"+"<<s.ao<<"i"<<endl;
return out;
}
istream& operator>>(istream& in,SOPHUC &p)
{
cout<<"\nNhap so phuc: ";
cin>>p.thuc>>p.ao;
return in;
}
SOPHUC SOPHUC::operator +(SOPHUC s2)
{
SOPHUC s3;
s3.thuc=this->thuc+s2.thuc;
s3.ao=this->ao+s2.ao;
return s3;
}
SOPHUC SOPHUC::operator -(SOPHUC s2)
{
SOPHUC s3;
s3.thuc=this->thuc-s2.thuc;
s3.ao=this->ao-s2.ao;
return s3;
}
phần main:
- Code:
void main()
{
clrscr();
SOPHUC S[300];
int i,n;
float thuc,ao;
cout<<"\nNhap so phan tu: "; cin>>n;
for (i=0;i<n;i++) cin>>S[i];
cout<<"\nDay so phuc: \n";
for (i=0;i<n;i++) cout<<S[i];
SOPHUC tong,tich;
for (i=0;i<n;i++) tong=tong+S[i];
cout<<"\nTong cac so phuc: "; tong.hienthi();
for (i=0;i<n;i++) tich=tich*S[i];
cout<<"\nTich cac so phuc: "; tich.hienthi();
SOPHUC x;
for (i=0;i<n;i++)
for (int j=i+1;j<n;j++)
if (S[i]>S[j])
{
x=S[i];
S[i]=S[j];
S[j]=x;
}
cout<<"\nDay sau khi sap xep\n";
for (i=0;i<n;i++) cout<<S[i];
SOPHUC M;
cout<<"\nNhap M: "; cin>>M;
for (i=0;i<n;i++)
if (M==S[i]) cout<<"\nTim thay "<<S[i];
else cout<<"\nKhong tim thay";
getch();
}
Bài làm tham khảo:
- Code:
#include<iostream.h>
#include"stdio.h"
#include<conio.h>
#include<math.h>
class so_phuc
{
private:
float thuc,ao;
public:
so_phuc()
{
thuc=0;
ao=0;
}
void nhap();
void hienthi();
void cong(so_phuc&,so_phuc&);
void tru(so_phuc&,so_phuc&);
void nhan(so_phuc&,so_phuc&);
void chia(so_phuc&,so_phuc&);
};
void so_phuc::nhap()
{
cout<<"\n Phan thuc:";cin>>thuc;
cout<<" Phan ao:";cin>>ao;
}
void so_phuc::hienthi()
{
cout<<thuc;
if(ao<0);
else cout<<"+";
cout<<ao<<"i";
}
void so_phuc::cong(so_phuc&z1,so_phuc&z2)
{
this->thuc=z1.thuc+z2.thuc;
this->ao=z1.ao+z2.ao;
}
void so_phuc::tru(so_phuc&z1,so_phuc&z2)
{
this->thuc=z1.thuc-z2.thuc;
this->ao=z1.ao-z2.ao;
}
void so_phuc::nhan(so_phuc&z1,so_phuc&z2)
{
this->thuc=z1.thuc*z2.thuc-z1.ao*z2.ao;
this->ao=z1.thuc*z2.ao+z1.ao*z2.thuc;
}
void so_phuc::chia(so_phuc&z1,so_phuc&z2)
{
so_phuc kq;
if((z2.thuc==0)&&(z2.ao==0)) return;
kq.thuc=z2.thuc/(pow(z2.thuc,2)+pow(z2.ao,2));
kq.ao=-z2.ao/(pow(z2.thuc,2)+pow(z2.ao,2));
(*this).nhan(z1,kq);
}
void main()
{
so_phuc z1,z2;
so_phuc kq;
clrscr();
cout<<" Moi ban nhap vao hai so phuc"<<endl;
cout<<" So thu nhat:";
z1.nhap();
cout<<" So thu hai:";
z2.nhap();
cout<<" So thu nhat:";z1.hienthi();
cout<<"\n So thu hai:";z2.hienthi();
cout<<"\n Ket qua cac phep toan:\n";
cout<<" Phep cong so hai so:";
kq.cong(z1,z2);
kq.hienthi();
cout<<"\n Phep tru so thu nhat cho so thu hai:";
kq.tru(z1,z2);
kq.hienthi();
cout<<"\n Phep nhan hai so:";
kq.nhan(z1,z2);
kq.hienthi();
cout<<"\n Phep chia so thu nhat cho so thu hai:";
kq.chia(z1,z2);
kq.hienthi();
cout<<"\n CHUC BAN THANH CONG";
fflush(stdin);getch();
}