#ifndef __MYSTRING_H_
#define __MYSTRING_H_
#include <iostream>
#include <cstring>
using namespace std;
class MyString
{
private:
char *m_data;
public:
MyString(const char * ptr=NULL)
{
cout << "constructor from one..." << endl;
if (ptr == NULL)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int len = strlen(ptr);
m_data = new char[len+1];
strcpy(m_data, ptr);
}
}
MyString(const MyString &other)
{
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data, other.m_data);
cout << "constructor from two ..." << endl;
}
MyString & operator=(const MyString& other)
{
if (this == &other)
{
return *this;
}
else
{
delete[] m_data;
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data, other.m_data);
return *this;
}
}
~MyString()
{
delete[] m_data;
m_data = NULL;
cout << "destructor..."<<endl;
}
};
#endif //__MYSTRING_H_
C++面试题之String类的构造函数,析构函数与赋值函数编写
最新推荐文章于 2022-04-18 16:39:44 发布