一个简单的版本
#include <iostream>
#include <cstring>
class MyString{
public:
typedef size_t size_type;
public:
MyString(){}
explicit MyString( int n, char ch = 0 ) : n_(n) {
ptr_ = new char[n_ + 1];
for( int i = 0; i < n_; ++i ){
ptr_[i] = ch;
}
ptr_[n_] = 0;
}
MyString( const char* str ){
n_ = strlen(str);
ptr_ = new char[ n_ + 1 ];
strncpy( ptr_, str, n_ + 1);
}
MyString( const MyString& rhs ){
n_ = rhs.size();
ptr_ = new char[n_ + 1];
for( int i = 0; i < n_; ++i ){
ptr_[i] = rhs.ptr_[i];
}
ptr_[n_] = 0;
}
MyString& operator=( const MyString& rhs ){
if( &rhs != this ){
delete [] ptr_;
n_ = rhs.size();
ptr_ = new char[n_ + 1];
for( int i = 0; i < n_; ++i ){
ptr_[i] = rhs.ptr_[i];
}
ptr_[n_] = 0;
}
return *this;
}
~MyString(){
delete [] ptr_;
}
size_type size() const { return n_; }
friend std::ostream& operator<<( std::ostream& os, const MyString& s );
private:
char* ptr_;
int n_;
};
std::ostream& operator<<( std::ostream& os, const MyString& s ){
if( os ){
os << s.ptr_;
}
return os;
}
int main(){
MyString s2 = "hello, world!";
std::cout << s2 << std::endl;
}