Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <iostream>
- using namespace std;
- class String {
- public:
- String() {
- size_ = 0;
- capacity_ = 15;
- str_ = new char[capacity_];
- }
- String(const int string_capacity) {
- size_ = 0;
- capacity_ = string_capacity;
- str_ = new char[capacity_];
- }
- String(const char* new_string) {
- capacity_ = strlen(new_string) + 1;
- str_ = new char[capacity_];
- strcpy(str_, new_string);
- size_ = capacity_ - 1;
- }
- void set_string(const char* new_string) {
- int new_space = strlen(new_string) + 1;
- if (capacity_ < new_space) {
- delete[] str_;
- capacity_ = new_space;
- str_ = new char[capacity_];
- }
- strcpy(str_, new_string);
- size_ = capacity_ - 1;
- }
- const char* get_string() {
- return str_;
- }
- void set_char(const int index, const char ch) {
- if (index < 0 || index >= size_) {
- cout << "Некорректный индекс" << endl;
- return;
- }
- str_[index] = ch;
- }
- char get_char(const int index) {
- if (index < 0 || index >= size_) {
- cout << "Некорректный индекс" << endl;
- // здесь функция возвращает char поэтому выйти по return не получится, использовать abort() можно, но тоже не лучший выход, пока пусть будет так, потом обработаем эту ситуацию с помощью исключений
- }
- return str_[index];
- }
- int size() {
- return size_;
- }
- int capacity() {
- return capacity_;
- }
- ~String() {
- delete[] str_;
- }
- private:
- char* str_;
- int size_;
- int capacity_;
- };
- int main() {
- setlocale(LC_ALL, "ru");
- String str1;
- String str2(30);
- String str3("Привет");
- cout << str3.get_string() << endl;
- str3.set_string("Новая строка");
- cout << str3.get_string() << endl;
- str1.set_string("Еще одна новая строка");
- cout << str1.get_string() << endl;
- }
Add Comment
Please, Sign In to add comment