题目:
运算符重载——重载赋值运算符=用于字符串赋值
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;
}
本文介绍了一个简单的字符串类实现,并详细展示了如何通过重载赋值运算符来实现字符串对象之间的赋值操作。文章包含了一个完整的C++代码示例,用于演示如何创建字符串类、定义必要的构造和析构函数、实现赋值运算符重载,并最终测试这些功能。
6382

被折叠的 条评论
为什么被折叠?



