#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class String
{
public:
String()
{
//cout << "无参构造函数" << endl;
m_psz = NULL;
m_length = 0;
}
String(const char* psz)
{
cout << "有参构造函数" << endl;
if (psz)
{
m_length = strlen(psz);
m_psz = new char[m_length + 1];
strcpy(m_psz, psz);
}
}
String(String& str)
{
cout << "拷贝构造函数" << endl;
m_length = str.m_length;
if (str.m_psz)
{
m_psz = new char[m_length + 1];
strcpy(m_psz, str.m_psz);
}
else
m_psz = NULL;
}
~String()
{
printf("析构函数被调用,m_psz的地址为%p\n", m_psz);
if (m_psz)
delete[]m_psz;
}
//必须返回一个新的对象
String operator+(String& str)
{
//cout << "+重载函数,String&" << endl;
if (str.m_psz)
{
String tmp;
tmp.m_length = str.m_length;
tmp.m_psz = new char[tmp.m_length + 1];
strcpy(tmp.m_psz, str.m_psz);
return tmp;
}
else
return *this;
}
//必须返回一个新的对象
String operator+(char* psz)
{
//cout << "+重载函数,char*" << endl;
if (psz)
{
int len = m_length + strlen(psz);
char* tmp = new char[len + 1];
tmp[len] = 0;
strcpy(tmp, m_psz);
strcat(tmp, psz);
String str = tmp;//调用有参构造函数
delete []tmp;
return str;
}
else
return *this;
}
//因为是cout调用,所以不能是类成员函数;由于要访问类的私有成员,所以声明为友元
friend ostream& operator<<(ostream& obj, String& str);
//赋值运算符
String& operator=(String& str)
{
//cout << "=重载函数,String&" << endl;
if (m_psz)
{
delete []m_psz;
m_length = 0;
}
if (str.m_psz)
{
m_length = str.m_length;
m_psz = new char[m_length + 1];
strcpy(m_psz, str.m_psz);
}
return *this;
}
//赋值运算符
String& operator=(char* psz)
{
//cout << "=重载函数,char*" << endl;
if (m_psz)
{
delete []m_psz;
m_length = strlen(psz);
m_psz = new char[m_length + 1];
strcpy(m_psz, psz);
}
return *this;
}
//还可以继续重载比较运算符
//...
char* c_str()
{
return m_psz;
}
int length()
{
return m_length;
}
private:
char* m_psz;
int m_length;
};
ostream& operator<<(ostream& obj, String& str)
{
printf("%s",str.m_psz);
return obj;
}
class TestClass
{
public:
String f1()
{
String s = "hello";
return s;
}
};
int main()
{
TestClass tc;
char* psz = tc.f1().c_str();
printf("psz地址为%p\n", psz);
getchar();
return 0;
}
VC++运行结果