MyString类
MyString.h
# ifndef MYSTRING_H
# define MYSTRING_H # include <iostream>
using namespace std; class MyString
{ private : char * str = nullptr ; unsigned int MaxSize = 0 ; public : MyString ( ) ; MyString ( unsigned int n) ; MyString ( const char * S) ; MyString ( const MyString& S) ; MyString& operator = ( const MyString& S) ; ~ MyString ( ) ; MyString ( MyString && S) noexcept ; MyString& operator = ( MyString&& S) noexcept ; friend ostream& operator << ( ostream& Output, MyString& S) ; friend istream& operator >> ( istream& Input, MyString& S) ; char & operator [ ] ( unsigned int i) ;
} ;
# endif
MyString.c
# include "MyString.h"
unsigned int Length ( const char * S)
{ const char * p = S; unsigned int L = 0 ; while ( * p != '\0' ) { p++ ; L++ ; } return L;
}
MyString :: MyString ( )
{ cout << "无参构造函数:" ;
}
MyString :: MyString ( unsigned int n)
{ MaxSize = n + 1 ; str = new char [ MaxSize] { } ;
}
MyString :: MyString ( const char * S)
{ MaxSize = Length ( S) + 1 ; str = new char [ MaxSize] { } ; for ( unsigned int i = 0 ; i < ( MaxSize - 1 ) ; i++ ) { str[ i] = S[ i] ; } str[ MaxSize - 1 ] = '\0' ; cout << "有参构造函数:" ;
}
MyString :: MyString ( const MyString& S)
{ MaxSize = S. MaxSize; str = new char [ MaxSize] { } ; for ( unsigned int i = 0 ; i < MaxSize; i++ ) { str[ i] = S. str[ i] ; } cout << "拷贝构造函数:" ;
}
MyString& MyString:: operator = ( const MyString& S)
{ delete [ ] str; MaxSize = S. MaxSize; str = new char [ MaxSize] { } ; for ( unsigned int i = 0 ; i < MaxSize; i++ ) { str[ i] = S. str[ i] ; } cout << "拷贝赋值运算符重载:" ; return * this ;
}
MyString :: ~ MyString ( )
{ if ( str != nullptr ) delete [ ] str; cout << "析构函数" << endl;
}
MyString :: MyString ( MyString&& S) noexcept
{ delete [ ] str; MaxSize = S. MaxSize; str = S. str; S. str = nullptr ; cout << "移动构造函数:" ;
}
MyString& MyString:: operator = ( MyString&& S) noexcept
{ delete [ ] str; MaxSize = S. MaxSize; str = S. str; S. str = nullptr ; cout << "移动赋值运算符重载:" ; return * this ;
} ostream& operator << ( ostream& Output, MyString& S)
{ Output << S. str; return Output;
}
istream& operator >> ( istream& Input, MyString& S)
{ Input >> S. str; return Input;
} char & MyString:: operator [ ] ( unsigned int i)
{ return str[ i] ;
}
main.c
# include <iostream>
using namespace std; # include "MyString.h" MyString GetMyString ( void )
{ MyString temp = "C++" ; return temp;
} void MyString_Test ( void )
{ MyString S1; cout << "S1 " << endl; char str[ ] = { "Hello World!" } ; MyString S2{ str } ; cout << "S2 " << S2 << endl; MyString S3{ S2 } ; cout << "S3 " << S3 << endl; S1 = S3; cout << "S1 " << S1 << endl; MyString S4{ move ( S1) } ; cout << "S4 " << S4 << endl; S4 = GetMyString ( ) ; cout << "S4 " << S4 << endl; MyString S5{ 3 } ; S5[ 0 ] = 'A' ; S5[ 1 ] = 'B' ; S5[ 2 ] = 'C' ; cout << S5 << endl;
} int main ( )
{ MyString_Test ( ) ;
}
结果: