006
06.09.2007, 19:43 Uhr
xXx
Devil
|
C++: |
namespace my { #include <cstring> template<typename T> class string { public: string() : m_length(0) { m_data = new T[m_length + 1]; m_data[m_length] = 0; } string(T const * const str) : m_length(std::strlen(str)) { m_data = new T[m_length + 1]; std::memcpy(m_data, str, m_length * sizeof(T)); m_data[m_length] = 0; } string(const string&) : m_length(rhs.length()) { m_data = new T[m_length + 1]; std::memcpy(m_data, rhs.c_str(), m_length * sizeof(T)); m_data[m_length] = 0; } ~string() { delete [] m_data; }
public: T& operator[](std::size_t pos) { return m_data[pos]; } T const& operator[](std::size_t pos) const { return m_data[pos]; } string operator+(const string& rhs) { std::size_t len = m_length + rhs.length(); T* data = new T[len + 1]; std::memcpy(&data[0], m_data, m_length * sizeof(T)); std::memcpy(&data[m_length], rhs.c_str(), rhs.length()* sizeof(T)); data[len] = 0; string tmp(data); delete [] data; return tmp; }
void operator+=(const string& rhs) { string tmp(*this); m_length += rhs.length(); delete [] m_data; m_data = new T[m_length + 1]; std::memcpy(&m_data[0], tmp.c_str(), tmp.length() * sizeof(T)); std::memcpy(&m_data[tmp.length(), rhs.c_str(), rhs.length() * sizeof(T)); m_data[m_length] = 0; }
string& operator= (const string& rhs) { if (this == &rhs) return *this;
delete [] m_data; m_length = rhs.length(); m_data = new T[m_length + 1]; std::memcpy(m_data, rhs.c_str(), m_length * sizeof(T)); m_data[m_length] = 0; return *this; }
public: std::size_t length() const { return m_length; } T const* c_str()() const { return m_data; } T const& at(std::size_t pos) const { if (pos >= m_length) throw std::out_of_range("at"); return m_data[pos]; } T& at(std::size_t pos) { if (pos >= m_length) throw std::out_of_range("at"); return m_data[pos]; }
private: T* m_data; std::size_t m_length; };
typedef string<char> cstring; typedef string<wchar_t> wstring; };
|
C++: |
#include "my_string.h" #include <iostream>
int main() { my::cstring string("Das ist ja toll!"); std::cout << string.c_str() << " | " << string.length() << std::endl; my::wstring unicode(L"UNICODE 4-ever!"); std::wcout << unicode.c_str() << L" | " << unicode.length() << std::endl; }
|
Ehm deines ein wenig umgeformt ... ob es alles korrekt ist hab ich nicht geprüft ... ein wenig an den Standard angepasst usw... naja ... hab es aber nunmal noch nicht kompiliert ... sorry... Dieser Post wurde am 06.09.2007 um 19:44 Uhr von xXx editiert. |