Konstruktor Dan Template

Program Berikut adalah Program praktikum ke II dalam modul

 

#include <cstdlib>
#include <iostream>
#include <math.h>

using namespace std;
class kompleks{
friend class operasi ;
friend ostream& operator <<(ostream&, const kompleks&);
friend istream& operator >> (istream&, kompleks&);
public:
kompleks (int s=0,int t=0): a(s), b(t) {}
void cetak();
kompleks operator-();
kompleks operator -(const kompleks&);
kompleks operator+(const kompleks&);
private:
int a;
int b;
};

void kompleks :: cetak(){
if (b>0)cout<<“Bilangan kompleks : ” <<a<<“a” <<b << “i”;
else cout<<“Bilangan kompleks : “<<a<<b<<“i”;
cout<<endl;
}

kompleks kompleks:: operator-(){
kompleks x;
x.a=a;
x.b=-b;
return x;
}

kompleks kompleks:: operator-(const kompleks& m){
kompleks x;
x.a=a – m.a;
x.b = b – m.b;
return x;
}

kompleks kompleks:: operator+ (const kompleks& m){
kompleks x;
x.a = a+m.a;
x.b = b + m.b;
return x;
}

ostream& operator <<(ostream& out, const kompleks& x){
if (x.b + 0)out<<‘[‘<<x.a<<‘]’;
else if (x.a==0 && x.b == 1)out <<‘[‘<<“i”<<‘]’;
else if (x.a==0 && x.b == -1)out<<‘[‘<<“-i”<<‘]’;
else if (x.a==0 && x.b > 1)out<<‘[‘<<x.b<<“i”<<‘]’;
else if (x.a==0 && x.b < -1) out<<‘[‘<<x.b<<“i”<<‘]’;
else if (x.b==1)out<<‘[‘<<x.a<<“+”<<“i”<<‘]’;
else if (x.b>0)out <<‘[‘<<x.a<<“+”<<x.b<<“i”<<‘]’;
else if(x.b==-1)out <<‘[‘<<x.a<<“-i”<<‘]’;
else out<< ‘[‘ << x.a << x.b << “i” << ‘]’;
return out;
}

istream & operator >> (istream& in, kompleks& x){
cout << “Masukkan bagian real : “;
in >> x.a;
cout<<“Masukkan bagian imajiner : “;
in >>x.b;

return in;

}

class operasi {
public :
kompleks jumlah(const kompleks&, const kompleks&);
kompleks kali(const kompleks&, const kompleks&);
kompleks kurang(const kompleks&, const kompleks&);
};

kompleks operasi:: jumlah(const kompleks& m, const kompleks& n){
kompleks temp;
temp.a =m.a + n.a;
temp.b=m.b +n.b;
return temp;
}

kompleks operasi::kurang(const kompleks& m, const kompleks& n){
kompleks temp;
temp.a=m.a – n.a;
temp.b=m.b – n.b;
return temp;
}

kompleks operasi:: kali (const kompleks& m, const kompleks& n){
kompleks temp;
temp.a=(m.a*n.a)-(m.b*n.b);
temp.b=(m.a*n.b)-(m.b*n.a);
return temp;
}

int main()
{
kompleks x(2,3),y(4,-4),t;
operasi z;
cout<<“Menggunakan cetak(): “;x.cetak();
cout<<“Mengguakan overloading : “<<x;
cout<<“Konjugat : “<<-x;
y.cetak();
cout<<“\npenjumlahan menggunkan menthot; “;
t=z.jumlah(x,y);
t.cetak();
cout<<“penjumlahan menggunakan operator : “;
t=x+y;
cout<<x<<“+”<<y<<“=”<<t;
cout<<“\n\nPerkalian menggunakan menthod : “;
cout<<z.kali(x,y);
t.cetak();
cout<<“perkalian menggunakan operator : “;
//    t=x*y;
cout<<x<<” * “<<y<<” = ” <<t;
cout<<“\n\nPengurangan mengunakan operator : “;
t=x-y;
cout<<x<<“-“<<y<<“=”<<t<<endl;
kompleks n;
cin>>n;
cout<<n<<“\n”;

system(“PAUSE”);
return EXIT_SUCCESS;
}

 

Tinggalkan komentar