// strcpy ,
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdint.h>
using namespace std;
class MyClass
{
public:
MyClass();
~MyClass();
void foo(){cout << "A" << endl;}
private:
};
MyClass::MyClass()
{
}
inline MyClass::~MyClass()//
{
cout << "inline destructed." << endl;
}
class StringT
{
public:
StringT(const char *str = NULL); //
StringT(const StringT &other); //
StringT & operator=(const StringT &other); //
void Print(const StringT &other) const; // const
~StringT(void); //
private:
char *m_pdata;
};
StringT::~StringT(void)
{
delete m_pdata;
}
void StringT::Print(const StringT &other) const
{
int len = strlen(other.m_pdata);
char *p = other.m_pdata;
for (int i = 0; i < len; i++)
{
cout << *(p++);
}
cout << endl;
}
StringT::StringT(const char *str)
{
if (str == NULL)
{
m_pdata = new char[1];
*m_pdata = '\0';
}
else
{
int length = strlen(str);
m_pdata = new char[length + 1];
strcpy(m_pdata,str);
}
}
StringT::StringT(const StringT & other)
{
if (other.m_pdata == NULL)
{
m_pdata = new char[1];
*m_pdata = '\0';
}
else
{
int length = strlen(other.m_pdata);
m_pdata = new char[length + 1];
strcpy(m_pdata,other.m_pdata);
}
}
// ①
StringT& StringT::operator =(const StringT &other)
{
// 1
if (this == &other)
{
return *this;
}
// 2
delete m_pdata;
// 3 , other
int length = strlen(other.m_pdata);
m_pdata = new char[length + 1];
strcpy(m_pdata, other.m_pdata);
return *this;
}
// ② offer 1
//StringT& StringT::operator =(const StringT &other)
//{
// if (this != &other)
// {
// StringT strTmp(other);
// char *pTmp = strTmp.m_pdata;
// strTmp.m_pdata = m_pdata;
// m_pdata = pTmp;
// }
// return *this;
//}
int main()
{
MyClass *P = new MyClass();
P->foo();
delete P;
StringT str("hello");
StringT s(str);
StringT t = s;
cout << "str = ";
str.Print(str);
cout << "s = ";
s.Print(s);
cout << "t = ";
t.Print(t);
return 0;
}