基礎を固める

4500 ワード

#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 ; d 1=d 2ポインタを直接付与し、operator=関数は呼び出されません
//3:operator=を行う場合は、元のスペースを外すことに注意
//4:delete d1,d2,d3;こんな愚かな表現