首页 > 代码库 > 【ThinkingInC++】62、类中指针

【ThinkingInC++】62、类中指针

类中指针

CopyingWithPointers.cpp

 


/**
* 书本:【ThinkingInC++】
* 功能:类中指针
* 时间:2014年10月4日14:26:19
* 作者:cutter_point
*/

#include "../require.h"
#include <iostream>
#include <string>

using namespace std;

class Dog
{
    string nm;
public:
    Dog(const string& name) : nm(name) {cout<<"Creating Dog: "<<*this<<endl;}
    //这里有一个类似于拷贝构造函数的函数
    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.nm<<"]";
    }
};

class DogHouse
{
    Dog* p;
    string houseName;
public:
    DogHouse(Dog* dog, const string house) : p(dog), houseName(house) {}

    //拷贝构造函数 Dog(const string& 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, "copy-construct")), houseName(dh.houseName+"copy-constructed") {}

    //为了避免自赋值,应该这样重载operator=
    DogHouse& operator=(const DogHouse& dh)
    {
        if(&dh != this)
        {
            p=new Dog(dh.p, "assigned");
            houseName=dh.houseName+" assigned";
        }

        return *this;
    }

    //改掉houseName的名字
    void renameHouse(const string& newName) {houseName=newName; }

    //得到dog这个对象
    Dog* getDog() const {return p;}

    //析构函数
    ~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、类中指针