面试题:
用c++编写类的String的构造函数、拷贝构造函数、析构函数和赋值函数
具体实现代码如下:
#include<iostream>
using namespace std;
class String
{
private:
char *p;
public:
String(const char*p); //普通构造函数
String(const String& other); //拷贝构造函数
String& operator=(const String& other); //赋值运算符重载函数
~String(void); //析构函数
char* C_str(void) const; //常量函数
};
String::String(const char*p)
{
cout << "String::String(const char*p)" << endl;
this->p = new char[strlen(p)+1]; //申请存放字符串的空间
strcpy(this->p,p); //用以传参
}
String::String(const String& other)
{
cout << "String::String(const String& other)" << endl;
this->p = new char[strlen(other.p)+1]; //自定义复制构造函数,避免指针的double free
strcpy(this->p,other.p);
}
String& String::operator=(const String& other)
{
cout << "operator=()is calling...." << endl;
if(this != &other)
{
char *tmp=new char[strlen(other.p)+1];
if( tm