运算符重载——重载赋值运算符=用于字符串赋值

来源:互联网 发布:淘宝野马软件 编辑:程序博客网 时间:2024/06/07 18:55

题目:

运算符重载——重载赋值运算符=用于字符串赋值

Time/Memory Limit:1000 MS/32768 K
Submitted: 72 Accepted: 44

Problem Description

定义一个字符串类,该类包括一个字符型指针数据成员,构造函数、析构函数、显示字符串函数,以及重载=运算符函数(用于字符串赋值)。在主函数中对字符串对象的赋值运算进行测试。

Input

输入数据有多行,每行包括一个字符串。

Output

输出有多行,对应每个输入数据要求输出两行,第一行是该输入的字符串对象,第二行是定义另一个对象进行赋值运算,将第一个对象赋值给第二个对象。

Sample Input

Hello!530 i think you!

Sample Output

Hello!Hello!530 i think you!530 i think you!

 

参考代码:

#include <iostream>
#include <string>
using namespace std;
class STRING{
private:
 char *ch;
public:
 STRING(char *c="NULL");
 STRING(STRING &);
 ~STRING();
 STRING& operator=(const STRING &);
 void show();
};
STRING::STRING(char *c){
 ch=new char[strlen(c)+1];
 strcpy(ch,c);
}
STRING::STRING(STRING &c){
 ch=new char[strlen(c.ch)+1];
 strcpy(ch,c.ch);
}
STRING::~STRING(){
 delete []ch;
}
STRING& STRING::operator=(const STRING &c){
 if(this==&c)
  return *this;
 delete []ch;
 ch=new char[strlen(c.ch)+1];
 strcpy(ch,c.ch);
 return *this;
}
void STRING::show(){
 cout<<ch<<endl;
}
int main()
{
 char c[21];
 while(gets(c))
 {
  STRING x(c),y;
  x.show();
  y=x;
  y.show();
 }
 return 0;
}

原创粉丝点击