VIP Указатели и ссылки в C++: полное руководство

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

8

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

Указатели и ссылки - важные концепции C++. Разберем их использование.

Указатели
Код:
#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 value = 42;
    int *ptr = &value;
    
    cout << "value: " << value << endl;
    cout << "*ptr: " << *ptr << endl;
    cout << "ptr: " << ptr << endl;
    cout << "&value: " << &value << endl;
    
    return 0;
}

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

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int *ptr = arr; // указатель на первый элемент
    
    // Доступ через указатель
    for(int i = 0; i < 5; i++) {
        cout << *(ptr + i) << " ";
    }
    cout << endl;
    
    // Альтернативный способ
    for(int i = 0; i < 5; i++) {
        cout << ptr[i] << " ";
    }
    cout << endl;
    
    return 0;
}

Динамическая память
Код:
#include <iostream>
using namespace std;

int main() {
    // Выделение памяти
    int *ptr = new int;
    *ptr = 100;
    cout << "Значение: " << *ptr << endl;
    
    // Освобождение памяти
    delete ptr;
    ptr = nullptr;
    
    // Динамический массив
    int size = 5;
    int *arr = new int[size];
    
    for(int i = 0; i < size; i++) {
        arr[i] = i * 2;
    }
    
    for(int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Освобождение массива
    delete[] arr;
    arr = nullptr;
    
    return 0;
}

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

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

Передача по ссылке
Код:
#include <iostream>
using namespace std;

// Передача по значению (копия)
void swapByValue(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}

// Передача по ссылке
void swapByReference(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

// Передача по указателю
void swapByPointer(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;
    
    cout << "До: x = " << x << ", y = " << y << endl;
    
    swapByReference(x, y);
    cout << "После swapByReference: x = " << x << ", y = " << y << endl;
    
    swapByPointer(&x, &y);
    cout << "После swapByPointer: x = " << x << ", y = " << y << endl;
    
    return 0;
}

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

int add(int a, int b) {
    return a + b;
}

int multiply(int a, int b) {
    return a * b;
}

int main() {
    int (*operation)(int, int);
    
    operation = add;
    cout << "Сложение: " << operation(5, 3) << endl;
    
    operation = multiply;
    cout << "Умножение: " << operation(5, 3) << endl;
    
    return 0;
}

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

int main() {
    // unique_ptr
    unique_ptr<int> ptr1 = make_unique<int>(100);
    cout << "Значение: " << *ptr1 << endl;
    
    // shared_ptr
    shared_ptr<int> ptr2 = make_shared<int>(200);
    shared_ptr<int> ptr3 = ptr2; // общий указатель
    cout << "Значение: " << *ptr2 << endl;
    cout << "Количество ссылок: " << ptr2.use_count() << endl;
    
    // weak_ptr
    weak_ptr<int> weak = ptr2;
    if(auto shared = weak.lock()) {
        cout << "Значение через weak_ptr: " << *shared << endl;
    }
    
    return 0;
}

Важные моменты:
- Всегда освобождайте динамическую память
- Используйте nullptr вместо NULL
- Проверяйте указатели перед использованием
- Предпочитайте ссылки указателям когда возможно

Указатели и ссылки - мощные инструменты C++!
 

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

Сверху