Показать сообщение отдельно

  #2  
Старый 01.10.2009, 08:26
sebay
Познающий
Регистрация: 09.03.2009
Сообщений: 43
С нами: 9039367

Репутация: 53
По умолчанию

кто-нибудь может переписать этот код в наиболее простой вид?

Код:
#ifndef MYSTRING_HPP
#define MYSTRING_HPP

#include <cstring> // memcpy, strlen
#include <cstdlib> // malloc, realloc

class MyString {
	private:
		char *data;
		size_t length;

	public:
		MyString() : data(0), length(0) { } // default constructor

		MyString(const char *str) {
			if (0 != str) {
				size_t size = std::strlen(str) + 1;
				length = size - 1;
				data = static_cast<char *>(std::malloc(size));
				std::memcpy(data, str, size);
			} else {
				length = 0;
				data = 0;
			}
		}

		MyString(const MyString& other) {
			length = other.length;
			data = static_cast<char *>(std::malloc(length + 1));
			std::memcpy(data, other.data, length + 1);
		}

		~MyString() {
			if (0 != data) {
				delete data;
			}
		}

		MyString& operator=(const MyString& rhs) {
			if (this == &rhs) {
				return *this;
			}
			length = rhs.length;
			data = static_cast<char *>(std::realloc(data, length + 1));
			std::memcpy(data, rhs.data, length + 1);
			return *this;
		}

		operator const char*() {
			return data; // unsafe
		}

		MyString& operator+=(const MyString& rhs) {
			data = static_cast<char *>(std::realloc(data, length + rhs.length + 1));
			std::memcpy(data + length, rhs.data, rhs.length + 1);
			length += rhs.length;
		}

		const MyString operator+(const MyString& rhs) const {
			return MyString(*this) += rhs;
		}

		char operator[](int idx) const {
			if (idx >= 0 && idx <= length) {
				return data[idx];
			}
		}

		char& operator[](int idx) {
			if (idx >= 0 && idx <= length) {
				return data[idx];
			}
		}
};

#endif
 
Ответить с цитированием