请教C++高手

来源:百度知道 编辑:UC知道 时间:2024/06/24 17:50:15
模拟C++标准库中的string容器 实现string类 支持下列程序:
int main()
{
string s1,s2,s3;
cin>>s1>>s2;
s3=s1+s2;
cout<<s3<<endl;
for(int i=0;i<s3.length();i++)
cout<<s3[i];
cout<<endl;
//
比较两个字符串的大小 按字符的顺序
if(s1>s2)
cout<<s1<<"is more lager than"<<s2<<endl;
cout<<s3.find(s2);
return 0;
}
要求:完成string类的构造函数,拷贝构造函数,析构函数,赋值运算符,比较运算符,加法运算符,流操作符,find函数,length函数,下标运算符

 
 
 
你可以好好地利用标准库里的 vector 类和 algorithm 里的一些演算法来大幅度地降低这项任务的难度:
(我没写拷贝构造函数、析构函数和赋值运算符,因为这个情况下编译器自动提供的不会造成问题)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class myString : private vector<char> {
public:
    myString( ) { }
    myString( char *cStr ) { assign( cStr, cStr + strlen( cStr ) ); }

    char operator[ ]( size_t i ) const { return vector<char>::operator[ ]( i ); }

    bool operator>( const myString& other )  const { return ! ( *this <= other ); }
    bool operator<( const myString& other )  const { return ! ( *this >= other ); }
    bool operator==( const myString& other ) const { return ! ( *this != other ); }