C++習(xí)題與解析(引用-04)

字號(hào):

題6.閱讀下面的程序與輸出結(jié)果,添加一個(gè)拷貝構(gòu)造函數(shù)來(lái)完善整個(gè)程序
    #include
    class Cat
    {
    public:
    Cat();
    Cat(const Cat &);
    ~Cat();
    int getage()const{return *itsage;}
    void setage(int age){*itsage=age;}
    protected:
    int *itsage;
    };
    Cat::Cat()
    {
    itsage=new int;
    *itsage=5;
    }
    Cat::~Cat()
    {
    delete itsage;
    itsage=0;
    }
    void main()
    {
    Cat frisky;
    cout<<"frisky’s age:"<    cout<<"setting frisky to 6...\n";
    frisky.setage(6);
    cout<<"creating boots from frisky\n";
    Cat boots(frisky);
    cout<<"frisky’s age:"<    cout<<"boots’age:"<    cout<<"setting frisky to 7...\n";
    frisky.setage(7);
    cout<<"frisky’s age:"<    cout<<"boots’age:"<    }
    當(dāng)添加了拷貝構(gòu)造函數(shù)后,程序的運(yùn)行結(jié)果為:
    frisky’s age:5
    setting frisky to 6...
    creating boots from frisky
    frisky’s age:6
    boots’age:6
    setting frisky to 7...
    frisky’s age:7
    boots’age:6
    解:
    添加的拷貝構(gòu)造函數(shù)如下:
    Cat::Cat(const Cat& c)
    {
    itsage=new int;
    *itsage=*c.itsage;
    }