VIP Классы и объекты в C++: основы ООП

Активный
Статус
Сообщения
516
Лайки
32

8

месяц на сайте

Классы - основа объектно-ориентированного программирования в C++. Разберем создание и использование.

Базовый класс
Код:
#include <iostream>
#include <string>
using namespace std;

class Person {
private:
    string name;
    int age;
    
public:
    // Конструктор
    Person(string n, int a) {
        name = n;
        age = a;
    }
    
    // Методы
    void display() {
        cout << "Имя: " << name << ", Возраст: " << age << endl;
    }
    
    void setName(string n) {
        name = n;
    }
    
    string getName() {
        return name;
    }
    
    void setAge(int a) {
        if(a > 0) {
            age = a;
        }
    }
    
    int getAge() {
        return age;
    }
};

int main() {
    Person person("John", 25);
    person.display();
    
    person.setName("Jane");
    person.setAge(30);
    person.display();
    
    return 0;
}

Конструкторы и деструкторы
Код:
#include <iostream>
#include <string>
using namespace std;

class Car {
private:
    string brand;
    int year;
    
public:
    // Конструктор по умолчанию
    Car() {
        brand = "Unknown";
        year = 0;
        cout << "Конструктор по умолчанию" << endl;
    }
    
    // Параметрический конструктор
    Car(string b, int y) {
        brand = b;
        year = y;
        cout << "Параметрический конструктор" << endl;
    }
    
    // Деструктор
    ~Car() {
        cout << "Деструктор для " << brand << endl;
    }
    
    void display() {
        cout << "Марка: " << brand << ", Год: " << year << endl;
    }
};

int main() {
    Car car1; // конструктор по умолчанию
    Car car2("Toyota", 2020); // параметрический конструктор
    
    car1.display();
    car2.display();
    
    return 0; // деструкторы вызываются автоматически
}

Наследование
Код:
#include <iostream>
#include <string>
using namespace std;

class Animal {
protected:
    string name;
    
public:
    Animal(string n) {
        name = n;
    }
    
    void speak() {
        cout << name << " издает звук" << endl;
    }
};

class Dog : public Animal {
public:
    Dog(string n) : Animal(n) {
    }
    
    void speak() {
        cout << name << " лает: Гав-гав!" << endl;
    }
    
    void fetch() {
        cout << name << " приносит мяч" << endl;
    }
};

class Cat : public Animal {
public:
    Cat(string n) : Animal(n) {
    }
    
    void speak() {
        cout << name << " мяукает: Мяу!" << endl;
    }
};

int main() {
    Dog dog("Бобик");
    Cat cat("Мурзик");
    
    dog.speak();
    dog.fetch();
    
    cat.speak();
    
    return 0;
}

Полиморфизм
Код:
#include <iostream>
using namespace std;

class Shape {
public:
    virtual void draw() {
        cout << "Рисование фигуры" << endl;
    }
    
    virtual double area() = 0; // чистая виртуальная функция
};

class Circle : public Shape {
private:
    double radius;
    
public:
    Circle(double r) {
        radius = r;
    }
    
    void draw() override {
        cout << "Рисование круга" << endl;
    }
    
    double area() override {
        return 3.14159 * radius * radius;
    }
};

class Rectangle : public Shape {
private:
    double width, height;
    
public:
    Rectangle(double w, double h) {
        width = w;
        height = h;
    }
    
    void draw() override {
        cout << "Рисование прямоугольника" << endl;
    }
    
    double area() override {
        return width * height;
    }
};

int main() {
    Shape *shape1 = new Circle(5.0);
    Shape *shape2 = new Rectangle(4.0, 6.0);
    
    shape1->draw();
    cout << "Площадь: " << shape1->area() << endl;
    
    shape2->draw();
    cout << "Площадь: " << shape2->area() << endl;
    
    delete shape1;
    delete shape2;
    
    return 0;
}

Инкапсуляция
Код:
#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;
    
public:
    BankAccount(double initialBalance) {
        if(initialBalance >= 0) {
            balance = initialBalance;
        } else {
            balance = 0;
        }
    }
    
    void deposit(double amount) {
        if(amount > 0) {
            balance += amount;
        }
    }
    
    bool withdraw(double amount) {
        if(amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
    
    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account(1000.0);
    
    account.deposit(500.0);
    cout << "Баланс после депозита: " << account.getBalance() << endl;
    
    if(account.withdraw(200.0)) {
        cout << "Снятие успешно" << endl;
    }
    
    cout << "Текущий баланс: " << account.getBalance() << endl;
    
    return 0;
}

Статические члены
Код:
#include <iostream>
using namespace std;

class Counter {
private:
    static int count;
    
public:
    Counter() {
        count++;
    }
    
    ~Counter() {
        count--;
    }
    
    static int getCount() {
        return count;
    }
};

int Counter::count = 0;

int main() {
    cout << "Начальное количество: " << Counter::getCount() << endl;
    
    Counter c1;
    Counter c2;
    Counter c3;
    
    cout << "Количество объектов: " << Counter::getCount() << endl;
    
    {
        Counter c4;
        cout << "Количество объектов: " << Counter::getCount() << endl;
    }
    
    cout << "Количество объектов: " << Counter::getCount() << endl;
    
    return 0;
}

Дружественные функции
Код:
#include <iostream>
using namespace std;

class Rectangle {
private:
    int width, height;
    
    friend void printDimensions(Rectangle r);
    friend class RectangleHelper;
    
public:
    Rectangle(int w, int h) {
        width = w;
        height = h;
    }
};

void printDimensions(Rectangle r) {
    cout << "Ширина: " << r.width << ", Высота: " << r.height << endl;
}

class RectangleHelper {
public:
    static void doubleSize(Rectangle &r) {
        r.width *= 2;
        r.height *= 2;
    }
};

int main() {
    Rectangle rect(10, 20);
    printDimensions(rect);
    
    RectangleHelper::doubleSize(rect);
    printDimensions(rect);
    
    return 0;
}

Важные моменты:
- Используйте инкапсуляцию для защиты данных
- Применяйте наследование для переиспользования кода
- Используйте виртуальные функции для полиморфизма
- Правильно управляйте памятью

Классы делают код более организованным и поддерживаемым!
 

0 человек читают эту тему (Всего: 0, Пользователей: 0, Гостей: 0)

Сверху