Классы в C++ — это основа объектно-ориентированного программирования (ООП). Они позволяют объединять данные (поля) и методы (функции) в единую сущность. Использование классов делает код более структурированным и удобным для расширения.
Определение класса
Класс объявляется с помощью ключевого слова class, после которого указываются его поля (переменные) и методы (функции).
class Point {
public:
int x;
int y;
Point(int xVal, int yVal) { // Конструктор
x = xVal;
y = yVal;
}
};
int main() {
setlocale(LC_ALL, "Russian");
Point p(10, 20); // Создание объекта с начальными значениями
cout << "Координаты: " << p.x << ", " << p.y << endl;
return 0;
}
class Car {
private:
string model;
int speed;
public:
void setModel(string m) { model = m; }
string getModel() { return model; }
void setSpeed(int s) {
if (s >= 0) speed = s;
}
int getSpeed() { return speed; }
};
class Animal {
public:
void makeSound() { cout << "Какой-то звук..." << endl; }
};
class Dog : public Animal {
public:
void makeSound() { cout << "Гав-гав!" << endl; }
};
class Animal {
public:
virtual void makeSound() { cout << "Животное издает звук" << endl; }
};
class Cat : public Animal {
public:
void makeSound() override { cout << "Мяу!" << endl; }
};
int main() {
setlocale(LC_ALL, "Russian");
Animal* a = new Cat();
a->makeSound(); // Выведет "Мяу!"
delete a;
return 0;
}
#include <iostream>
class Point {
public:
int x{ 0 };
int y{ 0 };
Point(int x, int y) {
if (x < 0 and y >= 0) {
this->x = 0;
this->y = y;
}
if (y < 0 and x >= 0) {
this->y = 0;
this->x = x;
}
if (y < 0 and x < 0) {
this->x = 0;
this->y = 0;
}
}
void print() {
std::cout << "x " << x << " y " << y << std::endl;
}
};
int main() {
Point test(10, -10);
test.print();
return 0;
}