#include <iostream>
#include <stdlib.h>
using namespace std;
class C
{
int * iCount;
public:
/* 这个函数是脱裤子打屁多此一举.
void clear()
{
if(iCount) delete iCount;
}
*/
C(){iCount = new int(0);} // intialize the memory pointed by iCount
// with 0;
// copy constructor and operator= is very importan in this case!
// here, using deep copy and assignment simply.
C(const C &rhv)
{ iCount = new int;
if(iCount == NULL)
{
cout << "memory overflow!" << endl;
exit(-1);
}
*iCount = *rhv.iCount;
}
C& operator=(const C &rhv)
{
*iCount = *rhv.iCount;
return *this;
}
~C()
{
delete iCount; // Don't need to check if iCount is a null pointer.
iCount = NULL; // turn icount into a null pointer is good,
// omit this step is ok too;
}
// for print.
friend ostream& operator<<(ostream& os, const C &c)
{
return os << *c.iCount;
}
// for test;
C(int i)
{
iCount = new int(i);
if(iCount == NULL)
{
cout << "memory overflow!" << endl;
exit(-1);
}
}
};
int main() {
C a;
cout << "a = " << a << endl;
C *pb = new C(999);
cout << "*pb = " << *pb << endl;
C *pc = new C(*pb);
cout << "*pc = " << *pc << endl;
delete pc;
C *pd =new C(888);
*pb = *pd;
cout << "*pb = " << *pb << endl;
delete pb;
cout << "*pd = " << *pd << endl;
delete pd;
system("pause");
return 0;
}