定义字符类string,并重载运算符成员函数+和=,使得string的对象可以执行如x=y+z这样的操作

zpjoker 2014-11-26 08:24:10
定义字符类string,并重载运算符成员函数+和=,使得string的对象可以执行如x=y+z这样的操作,表达式x=y+的运算结果是对象x中的字符串是对象y和z中字符串的连接。请用C++写出相关程序。
...全文
780 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangyunzhao 2014-12-05
  • 打赏
  • 举报
回复
直接抄std::string吧,看不到vc的stl,就看sgi的stl
zacharyLiu 2014-12-05
  • 打赏
  • 举报
回复

string string::operator + (const string &other)
{
	string stmp;
	stmp.m_string = new char[strlen(m_string)+strlen(other.m_string)+1];
	strcpy(stmp.m_string, m_string);
	strcat(stmp.m_string, other.m_string);
	return stmp;
}
string string::operator = (const string &other)
{
	if (this->m_string == other.m_string)
	{
		return *this;
	}
	m_string = new char[strlen(other.m_string)+1];
	strcpy(this->m_string,other.m_string);
	return *this;
}

测试可用
ztenv 版主 2014-11-26
  • 打赏
  • 举报
回复
即使自己重新写也不难吧?
爱喝雪花啤酒 2014-11-26
  • 打赏
  • 举报
回复
strcat
bbc611730122 2014-11-26
  • 打赏
  • 举报
回复
重载运算符成员函数+ 的声明应该是string operator+(string& other),刚才写错了
bbc611730122 2014-11-26
  • 打赏
  • 举报
回复
string& operator=(string& other) { if(p == other.p) return *this; delete p; p = new char[strlen(other.p)+1]; strcpy(p, other.p); return *this; } string& operator+(string& other) { string str; str.p = new char[strlen(p) + strlen(other.p) + 1]; strcpy(str.p, p); strcat(str.p, other.p); return str; }
zpjoker 2014-11-26
  • 打赏
  • 举报
回复
对的,而且不是太懂。
ri_aje 2014-11-26
  • 打赏
  • 举报
回复
抄一下 std::string 的呗。
熊熊大叔 2014-11-26
  • 打赏
  • 举报
回复
要交作业了?
yx02080802 2014-11-26
  • 打赏
  • 举报
回复
哦,待我思考思考
zpjoker 2014-11-26
  • 打赏
  • 举报
回复
会就会,告诉我,教一下我,我十分感谢你;但是光说这些没用,解决不了问题。

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧