1.示例代码
#include<bits/stdc++.h>
using namespace std;
class String
{
public:
String():_size(0), _str(NULL){ }
String(char *str);
String(const String &des);
String & operator=(const String &des);
static int getStrNum(){return _strnum;}
friend strSwap(String &first, String &second);
friend ostream& operator<<(ostream &os, const String &src);
~String();
private:
int _size;
char* _str;
static int _strnum;
};
int String::_strnum = 0;
String::String(char *str) //构造函数
{
cout<<"String::String(char *str)"<<endl;
_size = strlen(str);
_str = new char[_size+1];
strcpy(_str, str);
_strnum++;
}
String::String(const String &des) //拷贝构造函数
{
cout<<"String::String(const String &des)"<<endl;
_size = des._size;
_str = new char[_size+1];
strcpy(_str, des._str);
_strnum++;
}
strSwap(String &first, String &second)
{
swap(first._size, second._size);
swap(first._str, second._str);
}
//没有考虑异常安全
//String & String::operator=(const String &des) //等号运算符重载
//{
// cout<<"String & String::operator=(const String &des)"<<endl;
// if(this == &des)
// {
// return *this;
// }
//
// if(NULL != _str)
// {
// delete[] _str;
// _strnum--;
// }
//
// _size = des._size;
// _str = new char[_size+1];
// strcpy(_str, des._str);
// _strnum++;
//}
//考虑异常安全
String & String::operator=(const String &des) //等号运算符重载
{
cout<<"String & String::operator=(const String &des)"<<endl;
_strnum--;
String tmp(des);
strSwap(*this, tmp);
return *this;
}
ostream& operator<<(ostream &os, const String &src)
{
os<<"字符串:"<<src._str<<endl;
os<<"长度:"<<src._size<<"";
}
String::~String() //析构函数
{
cout<<"String::~String()"<<endl;
delete[] _str;
_str = NULL;
}
int main()
{
char* p = "Hello World!";
String str1(p);
cout<<str1<<endl;
cout<<"字符串个数:"<<String::getStrNum()<<endl;
cout<<"*****************************************"<<endl;
String str2("zhangling");
cout<<str2<<endl;
cout<<"字符串个数:"<<String::getStrNum()<<endl;
cout<<"*****************************************"<<endl;
str2 = str1;
cout<<str2<<endl;
cout<<"字符串个数:"<<String::getStrNum()<<endl;
cout<<"*****************************************"<<endl;
String str3 = str1;
cout<<str1<<endl;
cout<<"字符串个数:"<<String::getStrNum()<<endl;
cout<<"*****************************************"<<endl;
return 0;
}
2.运行结果