Добавил:
vvrstcnho
Рад, если кому-то помог
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабораторные работы С++ (для ИВТ) / Готовые лабы С++ / Лаба4 / Laba 4 (10)
.cpp#include <iostream>
#include <locale>
#include <cstring>
using namespace std;
class my_str {
int length;
char* str;
void allocate_and_copy(const char* s) {
length = strlen(s);
str = new char[length + 1];
strcpy(str, s);
}
public:
// Конструкторы
my_str() : length(0), str(nullptr) {}
my_str(const char* s) {
allocate_and_copy(s);
}
// Конструктор копирования
my_str(const my_str& other) {
allocate_and_copy(other.str);
}
// Деструктор
~my_str() {
delete[] str;
}
// а) Присваивание
my_str& operator=(const my_str& other) {
if (this != &other) {
delete[] str;
allocate_and_copy(other.str);
}
return *this;
}
// б) Сложение
my_str operator+(const my_str& other) const {
char* new_str = new char[length + other.length + 1];
strcpy(new_str, str);
strcat(new_str, other.str);
my_str result(new_str);
delete[] new_str;
return result;
}
// в) Присваивание со сложением
my_str& operator+=(const my_str& other) {
char* new_str = new char[length + other.length + 1];
strcpy(new_str, str);
strcat(new_str, other.str);
delete[] str;
allocate_and_copy(new_str);
delete[] new_str;
return *this;
}
// г) Приведение к char*
operator char*() const {
return str;
}
// д) Ввод
friend istream& operator>>(istream& is, my_str& s);
void print() const {
if (str) cout << str;
cout << " (длина: " << length << ")" << endl;
}
};
istream& operator>>(istream& is, my_str& s) {
char buffer[1000];
char ch;
int i = 0;
// Пропускаем пробелы
while (is.get(ch) && (ch == ' ' || ch == '\t'));
if (ch != '\n' && !is.eof()) {
buffer[i++] = ch;
}
// Читаем до новой строки
while (is.get(ch) && ch != '\n') {
if (ch != ' ' && ch != '\t') {
buffer[i++] = ch;
}
}
buffer[i] = '\0';
delete[] s.str;
s.allocate_and_copy(buffer);
return is;
}
int main() {
setlocale(LC_ALL, "ru_RU.UTF-8");
my_str s1("Привет");
my_str s2(" мир");
cout << "s1 = "; s1.print();
cout << "s2 = "; s2.print();
my_str s3 = s1 + s2;
cout << "s1 + s2 = "; s3.print();
s1 += s2;
cout << "s1 += s2: "; s1.print();
cout << "Введите строку: ";
my_str s4;
cin >> s4;
cout << "Вы ввели: "; s4.print();
return 0;
}
Соседние файлы в папке Лаба4
