Contoh-contoh membuat program sederhana dengan
menggunakan Class, source codenya adalah sebagai berikut:
Contoh 1:
#include
<iostream>
/* run this program
using the console pauser or add your own getch, system("pause") or
input loop */
using namespace std;
class CRectangle{
int p,l;
public:
void set_values (int,int);
int luas (void) {return (p*l);}
};
void
CRectangle::set_values (int r, int s){
p=r;
l=s;
}
int main(int argc,
char** argv) {
CRectangle rect;
rect.set_values (2,6);
cout<<"Luas: "<<rect.luas();
return 0;
}
Contoh 2:
#include
<iostream>
/* run this program
using the console pauser or add your own getch, system("pause") or
input loop */
using namespace std;
class CRectangle {
int a, b;
public:
void set_values (int,int);
int area (void) {return (a*b);}
};
void
CRectangle::set_values (int x, int y){
a=x;
b=y;
}
int main(int argc,
char** argv) {
CRectangle rect, rectb;
rect.set_values (2,3);
rectb.set_values (4,3);
cout<<"Rect area:
"<<rect.area()<<endl;
cout<<"Rectb area:
"<<rectb.area()<<endl;
return 0;
}
Contoh 3:
#include
<iostream>
/* run this program
using the console pauser or add your own getch, system("pause") or
input loop */
using namespace std;
class p_panjang{
public:
int p,l;
int luas(){return (p*l);
}
};
int main(int argc,
char** argv) {
p_panjang a;
cout<<"Panjang =
";cin>>a.p;
cout<<"Lebar =
";cin>>a.l;
cout<<"Luas =
"<<a.luas();
return 0;
}
Contoh 4:
#include <iostream>
/* run this program
using the console pauser or add your own getch, system("pause") or
input loop */
using namespace std;
class p_panjang{
private:
int p,l;
public:
int luas (){return (p*l);}
void beri_nilai (int p1, int l1){p=p1; l=l1;}
};
int main(int argc, char**
argv) {
p_panjang a,b;
int x,y;
cout<<"Panjang =
";cin>>x;
cout<<"Luas =
";cin>>y;
a.beri_nilai(x,y);
b.beri_nilai(10,15);
cout<<"\nLuas a = "<<a.luas();
cout<<"\nLuas b = "<<b.luas();
return 0;
}
Tidak ada komentar:
Posting Komentar