class Person{
private :
int i ;
char buf[256] ;
public:
Person(){}; //default constructor
~Person(){};
Person& operator= (Person& const other) // assignment constructor
{
if ( this == &other ) //判断两个对象地址是否是同一个
{
return *this;
}else
{
//先检查本身的old buf是否被清除
if ( buf != NULL)
{
memset(buf,0,sizeof(buf));
}
i = other.i ;
strcpy(buf,other.buf);
return *this;
}
}
Person (Person& rhs) //copy assignment c constructor
{
i = rhs.i ;
//先检查本身的old buf是否被清除
if ( buf != NULL)
{
memset(buf,0,sizeof(buf));
}
strcpy(buf,rhs.buf);
}
Person( char* p)
{
memset(buf,'\0',sizeof(buf));
strcpy(buf,p);
}
};
class Test2
{
public:
Test2(){ m_pChar = NULL;} //当拷贝构造时,不执行
Test2(char *pChar) { m_pChar = pChar;}
Test2(int num)
{
m_pChar = new char[num];
for(int i = 0; i< num; ++i)
m_pChar[i] = 'a';
m_pChar[num-1] = '\0';
}
Test2(const Test2& test)
{
//先判断本身是否已经指向非空内存块
if(!m_pChar )
{
delete []m_pChar;
m_pChar = NULL ;
}
m_pChar = new char[strlen(test.m_pChar)];
strcpy(m_pChar, test.m_pChar);
}
Test2& operator = (const Test2& test)
{
if(this == &test)
return *this;
//先判断本身是否已经指向非空内存块
if(m_pChar != NULL)
{
delete []m_pChar;
m_pChar = NULL ;
}
m_pChar = new char[strlen(test.m_pChar)];
strcpy(m_pChar, test.m_pChar);
return *this;
}
private:
char *m_pChar;
};
int main()
{
b_tree root = NULL;
int iarry[10] = {10,20,30,1,8,3,9,6,7,50};
//建立二叉树
root = create_btree(iarry,10);
//打印遍历二叉树
preOder(root);
Person p("hello");
Person pp(p); //拷贝构造
Person ppp = pp ; //拷贝构造
Person p1 ; //赋值构造
p1 = ppp;
Test2 t(5);
Test2 t2(t); //拷贝构造
Test2 t3 = t2;//拷贝构造
Test2 t4;
t4 = t; //赋值构造
Test2 t1(2);
Test2 t11(7);
t1 = t11 ;
return 0;
}
阅读(511) | 评论(0) | 转发(0) |