`

重新巩固下基础

阅读更多
#include <iostream>
#include <assert.h>
#include <vld.h>  //visual leak detected
//经visual leak detected测试,工作良好,无内存泄露
using namespace std ;

class base
{
public:
	base();
	base(int pi);
	virtual ~base();

	base(base& rhs);                         //拷贝
	base& operator=(const base& rhs);       //赋值

	void _set(int px, char *pp);
	void _print();
private:
	int i;
	char *p;
};

base::base()
{
	i = 0;
	p = NULL;
}

base::base(int pi):i(pi)
{
	p = NULL;
}


base::~base()
{
	delete []p; 
}

base::base(base &rhs)
{
	*this = rhs;
}

base& base::operator =(const base &rhs)
{
	cout<<"base ="<<endl;
	if( this==&rhs )
		return *this;

	if( rhs.p )
	{
		delete[] p;
		p = new char[ strlen(rhs.p)+1 ];
		strcpy(p, rhs.p);
	}
	else
	{
		p = new char[1];
		p[0]='\0';
	}

	i = rhs.i;
	return *this;
}

void base::_print()
{
	cout<<"base: "<<endl
		<<"i: "<<i<<endl;
	if (p)
	{
		cout<<"p: "<<p<<endl;
	}
	else
	{
		cout<<"p: "<<"NULL"<<endl;
	}
		
		
}

void base::_set(int px, char *pp)
{
	i = px;
	if(pp)
	{
		delete[] p;
		p = new char[strlen(pp)+1];
		strcpy(p, pp);
	}
}
/////////////////////////////////////
/////////////////////////////////////
/////////////////////////////////////
class derived:public base
{
public:
	derived();
	derived(int pi);
	derived(derived &rhs);
	~derived();

	derived& operator=(const derived &rhs);
	
	void _set(int px, char *pp);
	void _print();
private:
	int i;
	char *p;

};

derived::derived()
{
	i = 0;
	p = NULL;
}

derived::derived(int pi):base(pi),i(pi)
{
    p = NULL;
}

derived::derived(derived &rhs)
{
	*this = rhs;
}

derived& derived::operator=(const derived &rhs)
{
	cout<<"derived = "<<endl;
	if( this==&rhs)
		return *this;

	if( rhs.p)
	{
		delete []p;
		p = new char[ strlen(rhs.p)+1 ];
		strcpy(p, rhs.p);
	}
	else
	{
		p = new char[1];
		p[0] = '\0';
	}
	i = rhs.i;
	//基类赋值
	base::operator =(rhs);
	return *this;
}

derived::~derived()
{
	delete []p;
}

void derived::_print()
{
	cout<<"derived: "<<endl
		<<"i: "<<i<<endl;
	if (p)
	{
		cout<<"p: "<<p<<endl;
	}
	else
	{
		cout<<"p: "<<"NULL"<<endl;
	}
}

void derived::_set(int px, char *pp)
{
	i = px;
	if(pp)
	{
		delete[] p;
		p = new char[strlen(pp)+1];
		strcpy(p, pp);
	}
}
/////////////////////////////////////
/////////////////////////////////////
/////////////////////////////////////

int main()
{
/* 测试内存泄露情况
    base *b1=new base();
	base *b2=new base();
	derived *d1=new derived();
	derived *d2=new derived();

	b1->_set(10, "aaaa");
	b2->_set(20, "bbbb");
	d1->_set(30, "cccc");
	d2->_set(40, "dddd");

	*d1=*d2;
	*b1=*b2;
	b1->_print();

	delete b1;
	delete b2;
	delete d1;
	delete d2;
*/
	//测试基类赋值情况
    base *b1;
	derived d1(10);
	derived d2(20);

	d1._print();
	b1 = (base*)&d1;
	b1->_print();

	d1=d2;
	b1->_print();



	return 0;
}


//犯的错误 1:对char*进行构造函数初始化,这其实是个指针值的赋予,会造成释放的错
//误,并且建议两者要分开
//2:*d1,*d2 ; d1=d2, 对指针直接进行赋值,自然不会调用operator = 函数
//3:在进行operator=时,注意把原来的空间放掉
//4:delete d1,d2,d3;这样愚蠢的表达式


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics