Untitled
unknown
plain_text
2 years ago
3.6 kB
10
Indexable
#include <iostream>
#include <string>
// Интерфейсный класс Bird
class Bird {
public:
// Конструктор
Bird(std::string name) : name(name), id(++counter) {}
// Виртуальный деструктор
virtual ~Bird() {}
// Виртуальный метод 1
virtual void sing() const {
std::cout << "Bird " << name << " is singing." << std::endl;
}
// Виртуальный метод 2
virtual void fly() const {
std::cout << "Bird " << name << " is flying." << std::endl;
}
// Статический метод для получения количества созданных объектов
static int getCounter() {
return counter;
}
protected:
std::string name;
int id;
private:
// Статическое поле для подсчета созданных объектов
static int counter;
};
// Инициализация статического поля
int Bird::counter = 0;
// Класс, наследующий от Bird
class Songbird : public Bird {
public:
// Конструктор
Songbird(std::string name, std::string favoriteSong) : Bird(name), favoriteSong(favoriteSong) {}
// Переопределение виртуального метода 1
void sing() const override {
std::cout << "Songbird " << name << " is singing its favorite song: " << favoriteSong << std::endl;
}
// Переопределение виртуального метода 2
void fly() const override {
std::cout << "Songbird " << name << " is flying gracefully." << std::endl;
}
private:
std::string favoriteSong;
};
// Класс, наследующий от Bird и созданный шаблоном
template <typename T>
class SpecialBird : public Bird {
public:
// Конструктор
SpecialBird(std::string name, T specialData) : Bird(name), specialData(specialData) {}
// Переопределение виртуального метода 1
void sing() const override {
std::cout << "SpecialBird " << name << " is singing with special data: " << specialData << std::endl;
}
// Переопределение виртуального метода 2
void fly() const override {
std::cout << "SpecialBird " << name << " is flying uniquely." << std::endl;
}
private:
T specialData;
};
// Перегрузка оператора ввода
std::istream& operator>>(std::istream& input, Bird& b) {
std::cout << "Enter bird name: ";
std::getline(input, b.name);
return input;
}
int main() {
try {
Songbird songbird("Robin", "Chirp Chirp");
SpecialBird<int> specialBird("UniqueBird", 42);
std::cout << "Enter information for a new bird:" << std::endl;
Bird newBird;
std::cin >> newBird;
// Позднее связывание
Bird* birds[] = {&songbird, &specialBird, &newBird};
// Вывод информации о птицах и подсчет созданных объектов
for (int i = 0; i < 3; ++i) {
birds[i]->sing();
birds[i]->fly();
}
std::cout << "Total bird objects created: " << Bird::getCounter() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}Editor is loading...
Leave a Comment