Tiplarni dinamik tarzda
Download 1.83 Mb.
|
Tiplarni dinamik tarzda
1.4-dastur. Dinamik tipdagi identifikatsiya vositasidan foydalanish.
#include "stdafx.h" #include #include #include using namespace std; class figure { protected: double x, y; public: figure(double i, double j) { x = i; y = j; } virtual double area() = 0; }; class triangle : public figure { public: triangle(double i, double j) : figure(i, j) {} double area() { return x * 0.5 * y; } }; class rectangle : public figure { public: rectangle(double i, double j) : figure (i, j) {} double area() { return x * y;} }; class circle : public figure { public: circle(double i, double j=0) : figure(i, j) {} double area() {return 3.14 * x * x;} }; // figure sinf obʻyektlarini yaratish. figure *factory(){ switch(rand() % 3 ) { case 0: return new circle (rand()%15); case 1: return new triangle (rand()%15,rand()%15); case 2: return new rectangle (rand()%15, rand()%15); } return 0; }; int main(){ figure *p; // asos sinfga koʻrsatkich int i; int t=0, r=0, c=0; // 5 ta obʻyektlarni hosil qilsh va sanash for(i=0; i<15; i++) { p = factory(); // obʻyektni hosil qilish cout << "Obʻyektning tipi: " << typeid(*p).name(); cout << ". "; // obʻyektni tekshirish orqali sanasj if(typeid(*p) == typeid(triangle)) t++; if(typeid(*p) == typeid(rectangle)) r++; if(typeid(*p) == typeid(circle)) c++; // Yuzasini hisoblash cout << " S= " << p->area() << endl; } cout << endl; cout << "Quyidagi obʻyektlar hosil qilindi:\n"; cout << " Uchburchaklar: " << t << endl; cout << " Toʻrtburchaklar: " << r << endl; cout << " Doiralar: " << c << endl; system("pause"); return 0; } 1.4 – dastur natijasi. Output Obʻyektning tipi: class rectangle. S= 8 Obʻyektning tipi: class triangle. S= 28 Obʻyektning tipi: class circle. S= 28.26 Obʻyektning tipi: class triangle. S= 35 Obʻyektning tipi: class rectangle. S= 12 Obʻyektning tipi: class triangle. S= 55 Obʻyektning tipi: class rectangle. S= 72 Obʻyektning tipi: class circle. S= 254.34 Obʻyektning tipi: class rectangle. S= 21 Obʻyektning tipi: class triangle. S= 33 Obʻyektning tipi: class rectangle. S= 10 Obʻyektning tipi: class circle. S= 379.94 Obʻyektning tipi: class circle. S= 254.34 Obʻyektning tipi: class triangle. S= 4 Obʻyektning tipi: class triangle. S= 36 Quyidagi obʻyektlar hosil qilindi: Uchburchaklar: 6 Toʻrtburchaklar: 5 Doiralar: 4 Download 1.83 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling