谁能帮我写个c++程序?急要!!!

2024-12-26 02:53:17
推荐回答(1个)
回答1:

#include
using namespace std;
#include

class Str{
char * str;//指向保存字符串的空间
int len;//空间的大小
public:
Str();//无参构造,初始化成零长度字符串
Str(const char* sz);//用指定字符串初始化
Str(const Str&);//拷贝构造函数
~Str();//析构函数,清理空间
int Size() const;//取得字符串长度
Str& operator=(const Str&);//对象间赋值
friend Str operator+(const Str&,const Str&);
Str& operator+=(const Str&);//追加一个字符串
operator int()const;//类型转换函数
friend bool operator==(const Str&,const Str&);//字符串比较
friend ostream& operator<<(ostream& o, const Str&);//输出
friend istream& operator>>(istream& i,Str&);//输入
friend int operator >(const Str &s1,const Str &s2){return strcmp(s1.str,s2.str)>0;}
};
Str::Str()
{
len=100;
str = new char[100];
//if( str==NULL ){...}
str[0]='\0';//zero-length string
}
Str::Str( const char* sz )
{
if( sz==NULL )
sz = "";
len=strlen(sz)+1;
str = new char[len];
strcpy( str, sz );
}
Str::Str( const Str& cs )
:str(NULL),len(0)
{
*this=cs;//this->operator=(cs);
}
Str::~Str()
{
if( str )
delete[] str;
str = NULL;
len = 0;
}
Str& Str::operator=( const Str& cs )
{
int srclen= strlen(cs.str)+1;
if( srclen>len ){
if( str )
delete[] str;
str = new char[srclen];
//if( str==NULL ){...}
len=srclen;
}
strcpy( str, cs.str );
return *this;
}
int Str::Size()const
{
return strlen(str);
}
Str& Str::operator+=( const Str& app )
{
if( app.Size()==0 )
return *this;
int total=Size()+app.Size()+1;
if( total>len ){
char* temp=new char[total];
//if( temp==NULL ){...}
strcpy( temp, str );
delete[] str;
str = temp;
len = total;
}
strcat( str, app.str );
//strcpy( str+strlen(str), app.str );
return *this;
}
Str operator+(const Str& s1, const Str& s2)
{
Str s=s1;
s+=s2;
return s;
}
bool operator==(const Str& s1, const Str& s2)
{
return strcmp(s1.str,s2.str)==0;
}
Str::operator int()const
{
int sum=0;
for(int i=0;i {
if( str[i]<'0'||str[i]>'9' )
break;
sum = sum * 10 + str[i]-'0';
}
return sum;
}
ostream& operator<<(ostream&o,const Str&cs)
{
o< return o;
}
istream& operator>>(istream&i, Str&s)
{
char buf[1000];
i>>buf;
s=buf;
return i;
}

int main()
{
Str s1;
Str s2("Hello");
Str s3(s2);
s1=",world!";
cout<<"s1="< cout<<"s2="< cout<<"s3="< cout<<"s2==s3?"<<(s2==s3)< cout<<"s1==s3?"<<(s1==s3)< cout<<"s2>s3?"<<(s2>s3)< cout<<"s3>s1?"<<(s3>s1)< s3=s2+s1;
s2+=s1;
cout<<"s1="< cout<<"s2="< cout<<"s3="< cout<<"please input a word:"< cin>>s1;
cout<<"s1="< int value = s1;
cout<<"(int)s1="< return 0;
}