pta 运算符重载 自定义类mystring实现运算符=重载
自定义字符串类 mystring,包含私有成员变量char *buf;成员函数包括:无参构造函数(输出"construct 0")、带参构造函数(输出"construct 1")、析构函数(输出"destruct"),输出函数,并重载运算符=(分别用类mystring 和strcpy、strcat函数,在"c++"之后添加键盘输入字符串信息);在main()中分别定义2个 mystring类对象str1(ch)和str2,其中ch为字符数组(从键盘输入字符信息为其赋值),直接通过语句str2=str1;使str2中的信息赋值为“c++”与str1中字符串的连接结果,分别输出str1和str2的字符串。
输入格式:
在一行中给出字符个数不超过50的字符串。
输出格式:
分别输出构造和析构的提示信息,在2行中分别输出str1和str2的值。
输入样例:
在这里给出一组输入。例如:
hello
输入样例:
在这里给出一组输入。例如:
construct 1
hello
construct 0
c++hello
destruct
destruct
代码:
#include<iostream>
#include<string.h>
#define MAX 100
using namespace std;
class mystring {
private:
char* buf;
public:
mystring() {
buf = new char[MAX];
cout << "construct 0" << endl;
}
mystring(char *ch) {
buf = new char[MAX];
strcpy(buf,ch);
cout << "construct 1" << endl;
}
void operator=(mystring& s) {
strcpy(buf, "c++");
strcat(buf, s.buf);
}
void display() {
cout << buf << endl;
}
~mystring() {
delete buf;
cout << "destruct" << endl;
}
};
int main()
{
char* str=new char[MAX];
cin >> str;
mystring str1(str);
str1.display();
mystring str2;
str2 = str1;
str2.display();
return 0;
}