Good day!
It is necessary to create a class (a line ending with a terminal zero) and reload the operations “+” (string concatenation) and “[]” (insert a character). I coped with these tasks without difficulty, and it was time to start creating a destructor. And then it started ...
The bottom line is that when the “+” operation overload procedure starts, I create an additional variable k into which the first line is copied, and then the second one is added using strcat
. And, it would seem, everything is fine, but as soon as it comes to return
, the destructor cleans up the variable k and returns ... well, returns nonsense.
Not that I'm surprised by this event, I understand perfectly why this is happening, but I just can not solve this problem. Tell me how I can fix this joint.
Actually, the code:
#define _CRT_SECURE_NO_WARNINGS #include "stdafx.h" #include <iostream> #include <conio.h> #include <math.h> #include <string.h> #include <stdio.h> class stroka { private: char* s; int n; public: stroka(); //Конструктор по умолчанию stroka(int n1); //Конструктор с параметром void input(); //Функция ввода строки void output(); //Функция вывода строки на экран friend stroka& operator + (stroka& A, stroka& B); char& operator [] (int p) { return s[p]; } ~stroka(void); }; stroka::~stroka(void) { std::cout << "Очистка памяти" << std::endl; delete[] s; } stroka::stroka() { s = new char[1]; *s = 0; n = 0; } stroka::stroka(int n1) { s = new char[n1]; n = n1; } void stroka::input() { std::cout << "Введите строку: "; std::cin.getline(s, n, '\n'); } void stroka::output() { std::cout << "Введённая строка: " << s << std::endl << std::endl; } stroka& operator + (stroka& A, stroka& B) { stroka k(An + Bn); strcpy(ks, As); //Копируем 1-ую строку в новую strcat(ks, Bs); //Вставляем 2-ую строку в конец новой return k; } int _tmain(int argc, _TCHAR* argv[]) { setlocale(0, "Rus"); stroka A(10); stroka B(10); A.input(); //Ввод строки A.output(); //Вывод строки B.input(); B.output(); stroka C = A + B; C.output(); int pos; //Позиция вставки std::cout << "Номер позиции вставки элемента: "; std::cin >> pos; std::cout << "Введите элемент: "; char symbol; //Вставляемый символ std::cin >> symbol; C[pos] = symbol; C.output(); std::cout << endl << "Хорошего дня!"; _getch(); return 0; }