pta c++ 运算符重载 自定义类mystring实现运算符=重载

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;
}
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值