c++实现字符串的加法+和赋值=运算符的重载

c++中的operator特性可以帮助我们实现一些类特有的功能,帮助我们在对字符串操作中实现运算符的重载。

代码如下

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#pragma warning(disable:4996)
#include <string>

using namespace std;

class test_string{
	char *str;
public:
	test_string(char *string) {
		str = new char[strlen(string) + 1];
		strcpy(str, string);
		cout << "test() is called. str=" << str << endl;
	}
	~test_string(void){
		delete[] str;
		cout << "~test is called" << endl;
	}
	test_string& operator = (const test_string &para){
		if (this == &para)
		{
			return *this;
		}
		if (str != NULL)
		{
			delete[] str;
		}
		str = new char[strlen(para.str) + 1];
		strcpy(str, para.str);
		cout << "test_string& operator = (const test_string &para) is called. " << endl;
		return *this;
		
	}
	test_string& operator + (test_string &para){
		char *temp;
		temp = str;
		str = new char[strlen(str) + strlen(para.str) + 1];
		strcpy(str, temp);
		delete[] temp;
		strcat(str, para.str);
		cout << "test_string& operator + (test_string &para) is called. " << endl;
		return *this;
	}
	void print(void){
		cout << "str = " << str << endl;
	}
};

int main(int argc, char *argv[])
{
	test_string a("hello");//test() is called. str=hello
	test_string b("world");//test() is called. str=world
	cout << "*******************************" << endl;
	test_string c(" ");//test() is called. str=
	cout << "*******************************" << endl;
	c = c + a;//test_string& operator + (test_string &para) is called.   先加然后赋值
	a.print();//str = hello
	c.print();//str =  helloworld
	cout << "*******************************" << endl;
	c = c + b;//test_string& operator + (test_string &para) is called.   先加然后赋值
	b.print();//str = world
	c.print();//str =  helloworld
	cout << "*******************************" << endl;
	c = a + b;//test_string& operator + (test_string &para) is called.
			//test_string& operator = (const test_string &para) is called.
	a.print();//str = helloworld
	b.print();//str = world
	c.print();//str = helloworld
	cout << "*******************************" << endl;
	//a b c 的析构
	/*~test is called
~test is called
~test is called*/
	return 0;
}

执行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值