【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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值