#include <iostream>
#include <string.h>
using namespace std;
class String
{
public:
String(const char * str = NULL); //默认参数只需在函数声明时注明,函数定义时不需要
String(const String &other);
String & operator=(const String &other);
~String(void);
void output() { cout << m_data << endl; }
private:
char *m_data; //用于保存字符串
};
String::String(const char * str)
{
if (NULL == str)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
m_data = new char[strlen(str)+1];
strcpy(m_data, str);
}
cout << "Constructor is called" << endl;
}
String::String(const String &other)
{
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data, other.m_data);
cout << "Copy constructor is called" << endl;
}
String& String::operator=(const String &other)
{
if (this == &other) //不能写为if(*this == other),因为没有重载==,不能将两个类的对象做对比
{
return *this;
}
delete [] m_data;
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data, other.m_data);
cout << "Assignment operator is called" << endl;
return *this;
}
String::~String(void)
{
delete []m_data;
cout << "Destructor is called" << endl;
}
int main()
{
const char *c="hello";
String s(c); //Constructor is called
s.output();
String s2 = s; //Copy constructor
String s3(s2); //Copy constructor
s3 = s; //Assignment operator
return 0;
}
输出:
Constructor is called
hello
Copy constructor is called
Copy constructor is called
Assignment operator is called
Destructor is called
Destructor is called
Destructor is called