c++把char*包装成string

刚学了操作符重载,自己试着练习了一下

#include<iostream>
#pragma warning (disable:4996)
using namespace std;
class mystring {
	friend ostream& operator<<(ostream &os,  mystring const&  string1);
	friend istream& operator>>(istream &os, mystring& string);
public:
	mystring() {
		this->len = 0;
		this->string = NULL;
	}
	mystring(mystring const& another) {
		len = another.len;
		string = new char[len + 1];
		strcpy(string,another.string);
	}
	mystring(char const* another) {
		if (another == NULL) {
			len = 0;
			string = NULL;
		}
		else {
			len = strlen(another);
			string = new char[len + 1];
			strcpy(string, another);
		}
		
	}
	mystring(int len) {
		this->len = len;
		string = new char[len + 1];
		memset(this->string, 0, len + 1); //将此空间全部清零
	}
	mystring operator+(mystring another) {
		mystring temp(len + another.len);
		strcpy(temp.string, string);
		strcat(temp.string, another.string);
		return temp;
#if 0
		mystring temp;
		temp.len = this->len + another.len;
		temp.string = new char[(temp.len) + 1];
		strcpy(temp.string, string);
		strcat(temp.string,another.string);
		return temp;
#endif
	}
	char& operator[](int i) {
		return this->string[i];
	}
	bool operator==(const mystring &another)
	{
		if (strcmp(this->string, another.string) == 0) {
			return true;
		}
		else {
			return false;
		}
	}
	bool operator!=(const mystring &another)
	{
		return !(*this == another);
	}
private:
	int len;
	char* string;
};
ostream& operator<<(ostream &os,  mystring const &  string) {
	os << string.string;
	
	return os;
}
istream& operator>>(istream &is, mystring& string) {
	if (string.string != NULL) {
		delete[] string.string;
	}
	char temp[2048] = { 0 };
	is >> temp;
	string.len = strlen(temp);
	string.string = new char[string.len+1];
	strcpy(string.string, temp);
	return is;
}
int main() {
	mystring A("abc");
	mystring B = A;
	cout << A << endl;
	cout << B << endl;
	cout << (A + B) << endl;
	B[1] = 'g';
	cout << B << endl;
	cout << "输入B的新值:";
	cin >> B;
	cout << B << endl;;
	if (A == B) {
		cout << "输入的B和A相等" << endl;
	}
	else {
		cout << "输入的B和A不相等" << endl;
	}
	system("pause");
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值