面试题之c++String类的实现

已知类String的原型为:
class String
{
public:
String(const char *str = NULL);
String(const String &other);
String &operator=(const String &other);
String operator +(const String &other);
friend void showString(String &obj);
~String();
private:
char *m_data;


};       
请编写String的上述6个函数。


String::String(const char *str = NULL)
{
char *p=new char(strlen(str)+1)
strcpy(p,str);
this->m_data = p;
}
String::String(const String &other)
{
Char *p=new char(strlen(other.m_data)+1);
strcpy(p,other.m_data);
m_data=p;
}
String& String::operator=(const String &other)
{
Char *p=new char[strlen(other.m_data)+1];
strcpy(p,other.m_data);
this->m_data=p;
return *this;
}
String String::operator+(const String& other)
{
String Temp;
int size =strlen(this->m_data)+strlen(other.m_data)+1;
Char *p=new char[size];
strcpy(p,this->m_data);
strcat(p,other.m_data);
Temp.m_data=p;
return Temp;
}
void showString(String& obj)
{
cout<<obj.m_data<<endl;
}
String::~String()
{

        if(m_data!=NULL)

         {

                delete []m_data;

        }

}

切记,一定要使用深拷贝,不要使用浅拷贝,浅拷贝是有风险的,如果只是拷贝一个指针,那么当这个指针指向的内容被改变时,类的私有变量岂不是要被改变?

猜你喜欢

转载自blog.csdn.net/pycharm_u/article/details/79670912