Реализуем string спомощью malloc, strlen, strcpy и free.
Код mystring.cpp:
Код:
#include "mystring.h"
// Конструктор
MyString::MyString(char *value) {
this->value = (char *)malloc(strlen(value)); // резервирует память под переменную this->value
strcpy(this->value, value); // копируем строку из value в this->value
}
// Деструктор
MyString::~MyString() {
free(this->value); // освобождает память this->value
}
const char *MyString::get_value() {
return this->value; // возвращает this->value
}
int MyString::get_length() {
return strlen(this->value); // возвращает размер this->value
}
Код mystring.h:
Код:
#ifndef MYSTRING_H
#define MYSTRING_H
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
class MyString {
private:
char *value;
public:
MyString(char *value);
virtual ~MyString();
const char *get_value();
int get_length();
};
#endif
Пример код main.cpp:
Код:
#include <iostream>
#include "mystring.h"
using namespace std;
int main(int argc, char** argv) {
MyString str("Hello");
cout << str.get_value() << "\n" << str.get_length() << endl;
return 0;
}
Результат:
Код:
C:\mystringcpp>Project1.exe Hello 5