6-misol. Yuqoridagi misolni Animal massivi bilan ishlangan ko’rinishi
//Yuqoridagi sinflar yoziladi...
int main()
{
Cat matros("Matros"), ivan("Ivan"), martun("Martun");
Dog barsik("Barsik"), tolik("Tolik"), tyzik("Tyzik");
Animal *animals[] = { &matros, &barsik, &ivan, &tolik, &martun, &tyzik};
for (int i=0; i < 6; i++)
cout << animals[i]->getName() << " " << animals[i]->speak() << " deydi"<< '\n';
}
Mustaqil yechish uchun masalalar:
Mavzu yuzasidan misollar:
Barcha masalalar ajdod sinf obyektlarini qabul qiluvchi va qaytaruvchi funksiyani hosil qiling.
1. Brend, silindrlar soni, quvvat bilan tavsiflangan Car (Avtomobil) ajdod sinfini yarating. Quvvatni qayta tayinlash va o'zgartirish metodlarini aniqlang. Lorry (yuk mashinasi) sinfini yarating, shuningdek, kuzovning yuk ko'tarish qobiliyati xossasini qo‘shing. Brendni qayta belgilash va yuk ko'tarish qobiliyatini o'zgartirish funksiyalarini aniqlang.
#include
using namespace std;
class Car
{
protected:
string m_brend;
int m_countSilindr;
int m_power; //Quvvat
public:
Car(string brend, int countSilindr, int power)
{
m_brend = brend;
m_countSilindr = countSilindr;
m_power = power;
}
void setPower(int power)
{
m_power = power;
}
void setPowerN(int n)
{
m_power = n*m_power;
}
int getPower()
{
return m_power;
}
};
class Lorry: public Car
{
protected:
int m_baggage; //Yuk ko'tarish qobiliyati
public:
Lorry(int baggage): Car("Lorry",6,200)
{
m_baggage = baggage;
}
void setBrend(string brend)
{
m_brend = brend;
}
void setBaggage(int baggage)
{
m_baggage = baggage;
}
string getBrend()
{
return m_brend;
}
int getBaggage()
{
return m_baggage;
}
};
int main()
{
string brend;
int baggage;
Lorry lorry(2000);
cout<<"Yuk mashinasi brendining nomi "<cout<<"Yangi brend nomini kiriting: ";
getline(cin,brend);
cout<<"Yangi brend nomi: "<cout<<"Yuk ko'tarish qobiliyatini kiriting: ";
cin>>baggage;
lorry.setBaggage(baggage);
cout<<"Yuk ko'tarish qobiliyati: "<return 0;
}
3. Figure (Shakllar) nomli sinf hosil qiling. Undan To’g’ri to’rtburchak, Doira kabi sinflar vorislik olsin. Ajdod sinf tarkibida yuzani aniqlash virtual metodini hosil qiling.
#include
using namespace std;
class Figure
{
protected:
double m_x, m_y;
public:
Figure(double a = 0, double b = 0)
{
m_x = a;
m_y = b;
}
virtual double area()
{
return 0;
} // jimlik bo'yicha
};
class Rectangle : public Figure
{
public:
Rectangle(double a = 0, double b = 0) : Figure(a, b)
{
};
double area()
{
return(m_x*m_y);
}
};
class Circle : public Figure
{
public:
Circle(double a = 0) : Figure(a, 0) {};
double area()
{
return 3.1415*m_x*m_x;
}
};
int main()
{
Figure *shakl[2]; //Obyektlar massivini hosil qilish
Rectangle tugriTurtbuchak(3, 4); //To'g'ri to'rtburchak
Circle doira(2);
double total = 0;
shakl[0] = &tugriTurtbuchak;
shakl[1] = &doira;
cout<<"To'g'ri tortburchak yuzasi:"<< shakl[0]->area()<cout<<"Doira yuzasi:"<< shakl[1]->area()<return 0;
}
Do'stlaringiz bilan baham: |