Schreibe eine kleine String-Klasse. Denke dabei an C String Handling und an das RAII Idiom.
#include <iostream>
#include <utility> //für swap
#include <cstring> //für strcpy und strlen
using namespace std;
class String
{
private:
char* value;
public:
String(char const* value="")
: value(new char[strlen(value)+1])
{
strcpy(this->value, value);
}
String(String const& other)
: value(new char[other.length()+1])
{
strcpy(this->value, other.value);
}
~String()
{
delete [] value;
}
String const& operator=(String const& other)
{
String temp(other);
swap(temp);
return *this;
}
void swap(String& other)
{
::swap(value, other.value); //globales swap
}
char const* c_str() const
{
return value;
}
char& operator[](int index)
{
return value[index];
}
char const& operator[](int index) const
{
return value[index];
}
int length() const
{
return strlen(value);
}
};
int main()
{
String s;
String s1("Hallo Welt");
s=s1;
cout<<s.c_str()<<'\n';
}