pointer in class
CopyingWithPointers.cpp
/*** book: "thinkinginc++" * Function: pointer in class * Time: October 4, 2014 14:26:19* Author: cutter_point*/#include ". /require.h "#include <iostream> #include <string>using namespace Std;class dog{string Nm;public:dog (cons T string& name): NM (name) {cout<< "Creating Dog:" <<*THIS<<ENDL;} Here is a function similar to copy constructor Dog (const dog* DP, const string& MSG): NM (dp->nm+msg) {cout<< "Copied Dog" <<*this<< "from" <<*dp<<endl; } ~dog () {cout<< "Deleting Dog:" <<*THIS<<ENDL;} void rename (const string& newName) {nm=newname; cout<< "Dog Rename to:" <<*this<<endl; } Friend ostream& operator << (ostream& os, const dog& d) {return os<< "[" <<D.N m<< "]"; }};class doghouse{dog* p; String Housename;public:doghouse (dog* dog, const string House): P (dog), Housename (house) {}//copy constructor, Dog (const STR ing& name): NM (name) {cout<< "Creating Dog:" <<*THIS<<ENDL;} Dog (const dog* DP, const string& MSG): NM (DP->NM+MSG) Doghouse (const doghouse& DH): P (New Dog (DH.P, "Co Py-construct ")), Housename (dh.housename+" copy-constructed ") {}//In order to avoid self-assignment, this should overload operator= doghouse& operator= (CO NST doghouse& dh) {if (&DH! = this) {p=new Dog (DH.P, "assigned"); Housename=dh.housename+ "Assigned"; } return *this; }//Get rid of Housename's name void Renamehouse (const string& newName) {housename=newname;} Get the Dog This object dog* Getdog () const {return p;} destructor ~doghouse () {delete p;} Friend ostream& operator << (ostream& os, const doghouse& DH) {return os<< "[" <<dh .housename<< "] contains" <<*dh.p; }};int Main () {Doghouse Fidos (new Dog ("Fido"), "Fidohouse"); cout<<fidos<<endl; Doghouse Fidos2=fidos; cout<<fidos2<<endl; FIdos2.getdog ()->rename ("Spot"); Fidos2.renamehouse ("Spothouse"); cout<<fidos2<<endl; Fidos=fidos2; cout<<fidos<<endl; Fidos.getdog ()->rename ("Max"); Fidos2.renamehouse ("Maxhouse"); return 0;}
"Thinkinginc++" 62, pointer in class