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 ¶){
if (this == ¶)
{
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 ¶) is called. " << endl;
return *this;
}
test_string& operator + (test_string ¶){
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 ¶) 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 ¶) is called. 先加然后赋值
a.print();//str = hello
c.print();//str = helloworld
cout << "*******************************" << endl;
c = c + b;//test_string& operator + (test_string ¶) is called. 先加然后赋值
b.print();//str = world
c.print();//str = helloworld
cout << "*******************************" << endl;
c = a + b;//test_string& operator + (test_string ¶) is called.
//test_string& operator = (const test_string ¶) 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;
}