VIP Основы C++: введение для начинающих

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

8

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

C++ - мощный язык программирования. Разберем базовые концепции.

Структура программы
Код:
#include <iostream>
using namespace std;

int main() {
    cout << "Hello World" << endl;
    return 0;
}

Переменные и типы данных
Код:
#include <iostream>
using namespace std;

int main() {
    int age = 25;
    float price = 19.99;
    double precision = 3.14159;
    char grade = 'A';
    string name = "John";
    bool isActive = true;
    
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    return 0;
}

Ввод и вывод
Код:
#include <iostream>
using namespace std;

int main() {
    int number;
    string name;
    
    cout << "Введите ваше имя: ";
    cin >> name;
    
    cout << "Введите число: ";
    cin >> number;
    
    cout << "Привет, " << name << "! Вы ввели: " << number << endl;
    
    return 0;
}

Условные операторы
Код:
#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Введите возраст: ";
    cin >> age;
    
    if(age >= 18) {
        cout << "Взрослый" << endl;
    } else {
        cout << "Несовершеннолетний" << endl;
    }
    
    // Switch
    int day;
    cout << "Введите день недели (1-7): ";
    cin >> day;
    
    switch(day) {
        case 1:
            cout << "Понедельник" << endl;
            break;
        case 2:
            cout << "Вторник" << endl;
            break;
        default:
            cout << "Другой день" << endl;
    }
    
    return 0;
}

Циклы
Код:
#include <iostream>
using namespace std;

int main() {
    // For
    for(int i = 0; i < 10; i++) {
        cout << i << " ";
    }
    cout << endl;
    
    // While
    int i = 0;
    while(i < 10) {
        cout << i << " ";
        i++;
    }
    cout << endl;
    
    // Do-while
    int j = 0;
    do {
        cout << j << " ";
        j++;
    } while(j < 10);
    cout << endl;
    
    return 0;
}

Массивы
Код:
#include <iostream>
using namespace std;

int main() {
    // Одномерный массив
    int numbers[5] = {1, 2, 3, 4, 5};
    
    for(int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
    
    // Двумерный массив
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    
    return 0;
}

Функции
Код:
#include <iostream>
using namespace std;

// Объявление функции
int add(int a, int b);
void greet(string name);

int main() {
    int result = add(5, 3);
    cout << "Сумма: " << result << endl;
    
    greet("John");
    return 0;
}

// Определение функции
int add(int a, int b) {
    return a + b;
}

void greet(string name) {
    cout << "Привет, " << name << "!" << endl;
}

Указатели
Код:
#include <iostream>
using namespace std;

int main() {
    int number = 10;
    int *ptr = &number; // указатель на number
    
    cout << "Значение: " << number << endl;
    cout << "Адрес: " << ptr << endl;
    cout << "Значение через указатель: " << *ptr << endl;
    
    *ptr = 20; // изменение значения через указатель
    cout << "Новое значение: " << number << endl;
    
    return 0;
}

Ссылки
Код:
#include <iostream>
using namespace std;

int main() {
    int number = 10;
    int &ref = number; // ссылка на number
    
    cout << "Значение: " << number << endl;
    cout << "Ссылка: " << ref << endl;
    
    ref = 20; // изменение через ссылку
    cout << "Новое значение: " << number << endl;
    
    return 0;
}

Строки
Код:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = "World";
    
    // Конкатенация
    string result = str1 + " " + str2;
    cout << result << endl;
    
    // Длина строки
    cout << "Длина: " << result.length() << endl;
    
    // Подстрока
    string substr = result.substr(0, 5);
    cout << "Подстрока: " << substr << endl;
    
    // Поиск
    size_t pos = result.find("World");
    if(pos != string::npos) {
        cout << "Найдено на позиции: " << pos << endl;
    }
    
    return 0;
}

Структуры
Код:
#include <iostream>
#include <string>
using namespace std;

struct Person {
    string name;
    int age;
    float height;
};

int main() {
    Person person;
    person.name = "John";
    person.age = 25;
    person.height = 175.5;
    
    cout << "Имя: " << person.name << endl;
    cout << "Возраст: " << person.age << endl;
    cout << "Рост: " << person.height << endl;
    
    return 0;
}

Классы
Код:
#include <iostream>
#include <string>
using namespace std;

class Car {
private:
    string brand;
    int year;
    
public:
    Car(string b, int y) {
        brand = b;
        year = y;
    }
    
    void display() {
        cout << "Марка: " << brand << ", Год: " << year << endl;
    }
    
    void setBrand(string b) {
        brand = b;
    }
    
    string getBrand() {
        return brand;
    }
};

int main() {
    Car car("Toyota", 2020);
    car.display();
    
    car.setBrand("Honda");
    cout << "Новая марка: " << car.getBrand() << endl;
    
    return 0;
}

Работа с файлами
Код:
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    // Запись в файл
    ofstream outFile("data.txt");
    if(outFile.is_open()) {
        outFile << "Hello World" << endl;
        outFile << "Это тестовая строка" << endl;
        outFile.close();
    }
    
    // Чтение из файла
    ifstream inFile("data.txt");
    string line;
    if(inFile.is_open()) {
        while(getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    }
    
    return 0;
}

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

C++ - мощный язык для системного программирования!
 

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

Сверху