|
Mustaqil ishi Bajardi: Abdusoatov j tekshirdi: Qurbonov N
|
bet | 4/5 | Sana | 13.05.2024 | Hajmi | 0,54 Mb. | | #230132 |
Bog'liq Abdusoatov Javlonbek.override kalit so'zi bilan).
#include
#include
using namespace std;
class Animal {
public:
virtual void sound() const {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() const override {
cout << "Dog wow wow" << endl;
}
};
class Cat : public Animal {
public:
void sound() const override {
cout << "Cat meow meow" << endl;
}
};
int main() {
Animal *animal1 = new Dog();
Animal *animal2 = new Cat();
animal1->sound();
animal2->sound();
delete animal1;
delete animal2;
return 0;
}
Bu dasturda, "Shape" sinfi doirasida "Rectangle" va "Circle" sinflari yaratilgan. "Area" funksiyasi ularning hamma sinflari uchun virtual e'tibor qilinadi. "Rectangle" va "Circle" sinflarida esa "Area" funksiyasining mos ravishda qayta yozilishi (override kalit so'zi bilan) va ushbu sinflarga xos yuzalarni hisoblash imkoniyati berilgan.
#include
#include
using namespace std;
class Shape {
public:
virtual float Area() const = 0; // Virtual funksiya
};
class Rectangle : public Shape {
private:
float width;
float height;
public:
Rectangle(float w, float h) : width(w), height(h) {}
float Area() const override {
return width * height;
}
};
class Circle : public Shape {
private:
float radius;
public:
Circle(float r) : radius(r) {}
float Area() const override {
return M_PI * radius * radius;
}
};
int main() {
Shape* shapes[2];
shapes[0] = new Rectangle(5, 4);
shapes[1] = new Circle(3);
for (int i = 0; i < 2; ++i) {
cout << "Area of shape " << i + 1 << ": " << shapes[i]->Area() << endl;
}
delete shapes[0];
delete shapes[1];
return 0;
}
6-mavzuga oid dasturlar
Bu dasturda,
|
| |