一、编写MyString类
对于下面的类MyString,要求重载一些运算符后可以计算表达式a=b+c。
其中,a、b、c都是类MyString的对象。请重载相应的运算符并编写程序测试。
class MyString
{
char* str;
public:
MyString(char* s)
{
str = new char(strlen(s)+1);
strcpy(str, s);
}
~MyString()
{
delete []str;
}
};
解析:
为了实现a=b+c这个表达式,需要重载两个运算符,一个是‘+’,一个是‘=’,程序如下:
#include <iostream>
#include <string.h>
using namespace std;
class MyString
{
char* str;
public:
MyString(char* s)
{
str = new char(strlen(s)+1);
strcpy(str, s);
}
~MyString()
{
delete []str;
}
MyString & operator = (MyString &string) //重载=
{
if(this == &string)
{
return *this;
}
if(str != NULL)
{
delete []str;
}
str = new char[strlen(string.str)+1];
strcpy(str, string.str);
return *this;
}
MyString & operator + (MyString &string) //重载+ (改变被加对象)
{
char* temp = str;
str = new char[strlen(temp) + strlen(string.str) + 1];
strcpy(str, temp);
delete []temp;
strcat(str, string.str);
return *this;
}
/*
MyString & operator + (MyString & string) //重载+ (不改变被加对象)
{
MyString *pstring = new MyString("");
pstring->str = new char[strlen(str)+strlen(string.str)+1];
strcpy(pstring->str, str);
strcat(pstring->str, string->str);
return *pstring;
}*/
void print()
{
cout<<str<<endl;
}
};
/*
//MyString类的友元,要求str成员是public权限
MyString &operator + (MyString& right, MyString& left)
{
MyString* pstring = new MyString("");
pstring->str = new char[strlen(right.str)+strlen(left.str)+1];
strcpy(pstring->str, left.str);
strcat(pstring->str, right.str);
return *pstring;
}*/
int main()
{
MyString a("hello ");
MyString b("world");
MyString c("");
c = c + a;
c.print();
c = c + b;
c.print();
c = a + b;
a.print();
c.print();
return 0;
}
这里有三个版本的‘+’操作符重载函数,它们都是调用strcpy复制第一个字符串,然后调用strcat连接两个字符串。
第一个版本返回*this对象,它改变了被加对象的内容。使用第一个‘+’操作符重载函数版本的执行结果:
hello
hello world
hello world (对象a的str成员被改变了)
hello world
第二个版本和第三个版本都是返回堆中构造的对象,它们没有改变被加对象内容。它们的区别如下:
(1)第二个版本属于类的成员函数,而第三个版本是类的友元函数。
(2)第二个版本的参数为1个,而第三个版本的参数为2个,因为友元函数不含有this指针。
(3)由于类的友元函数不能使用私有成员,因此在这里使用第三个版本时需要把str成员的访问权限改为public。
使用这两个操作符重载函数版本的结果:
hello
hello world
hello (对象a的str成员没有被改变)
hello world
选择何种版本的‘+’操作符重载函数要取决于实际情况。
二、new操作符重载的使用
下面程序中主函数的new是类中new操作符重载。但是new后面只有一个参数0xa5,而类中函数的声明有两个参数。怎么调用这个类呢?
#include <iostream>
#include <malloc.h>
#include <memory.h>
using namespace std;
class Blanks
{
public:
void* operator new(size_t stallocateBlock, char chInit);
};
void* Blanks::operator new(size_t stallocateBlock, char chInit)
{
void* pvTemp = malloc(stallocateBlock);
if(pvTemp != 0)
{
memset(pvTemp, chInit, stallocateBlock);
}
return pvTemp;
}
int main()
{
Blanks *a5 = new(0xa5) Blanks;
return 0;
}
这里有一下几点需要说明:
(1)重载new操作符第一个参数必须是size_t类型,并且传入的值就是类的大小。
(2)代码25行中的0xa5表示第二个参数的大小,也就是chInit为0xa5.
(3)代码18行,用chInit初始化分配的那块内存。