{
public:
CMyString( const char *pData );
//CMyString(const CMyString &str);
CMyString(const CMyString *str);
~CMyString(void);
CMyString & operator = (const CMyString &str);
private:
char *m_pData;
};
CMyString::CMyString(const char *pData )
{
cout << "自定义构造函数" << endl;
if(pData == NULL)
{
m_pData = new char[1];
*m_pData = '\0';
}
else
{
int len = strlen(pData);
m_pData = new char[len + 1];
memcpy(m_pData,pData,sizeof(char)*(len+1));
}
}
CMyString::CMyString(const CMyString &str)
{
cout << "自定义拷贝构造函数" << endl;
int len = strlen(str.m_pData);
m_pData = new char[len +1];
memcpy(m_pData,str.m_pData,sizeof(char)*(len+1));
}
*/
CMyString::CMyString(const CMyString *str)
{
cout << "自定义拷贝构造函数 2" << endl;
int len = strlen(str->m_pData);
m_pData = new char[len +1];
memcpy(m_pData,str->m_pData,sizeof(char)*(len+1));
}
/*
CMyString & CMyString::operator = (const CMyString &str)
{
cout << "自定义赋值函数" << endl;
if(this == &str)
return *this;
delete [] m_pData;
m_pData = NULL;
m_pData = new char[strlen(str.m_pData)+1];
strcpy(m_pData,str.m_pData);
return *this;
}
*/
CMyString & CMyString::operator = (const CMyString &str)
{
cout << "自定义赋值函数2" << endl;
if(this != &str)
{
CMyString strTemp(str);
char *pTemp = strTemp.m_pData;
strTemp.m_pData = m_pData;
m_pData = pTemp;
}
return *this;
}
CMyString::~CMyString(void)
{
cout << "自定义析构函数" << endl;
delete [] m_pData;
}
void test()
{
cout << "a(\"abc\")" << endl;
CMyString a("abc");
//cout << "b(\"cde\")" << endl;
//CMyString b("cde");
//cout << " d = a" << endl;
//CMyString d = a;
//cout << "c(b)" << endl;
//CMyString *b = &a;
CMyString c(&a);
//cout << "c = a" << endl;
//c = a;
cout << endl;
}
总结
拷贝构造函数是对象被创建时调用,赋值函数只能被已经存在了的对象调用
注意浅复制与深复制区别
浅复制,同时指向同一块内存,谁来负责释放那块空间,很有可能导致同一块内存被释放两次
深复制,各自有各自申请的内存,各自负责释放各自申请的内存
当你不需要“重新指向”时,引用一般优先于指针被选用。
这通常意味着引用用于类的公有接口时更有用。
引用出现的典型场合是对象的表面,而指针用于对象内部。
class B
{
public:
B()
{
cout<<"default constructor"<<endl;
}
~B()
{
cout<<"destructed"<<endl;
}
B(int i):data(i)
{
cout<<"constructed by parameter "<< data <<endl;
}
B(B const &b)
{
cout<<"constructed by copye\n";
}
B & operator = (B const &b)
{
cout<<"constructed by =\n";
}
private:
int data;
};
B Play( B b)
//B Play( B &b)
{
return b ;
}
void test()
{
//B t2;
//B t1 = Play(t2);
B t1 = Play(5);
B t2;
t2 = t1;
}
int main()
{
test();
return 0;
}