大家看下,为什么这个程序里,构造函数Cat(const Cat &)里的初使化成员指针变量的时候要先动态开辟一个内存空间,
而成员函数void setage(int age)可要可不要呢?
#include "stdafx.h"
#include<iostream.h>
class Cat
{
public:
Cat();
//常引用,不允许改变引用的值
~Cat();
int getage()const{return *itsage;}
//void setage(int age){*itsage=age;}
void setage(int age);
protected:
int *itsage;
};
Cat::Cat()
{
itsage=new int;
*itsage=5;
}
Cat::Cat(const Cat & c)
{
//itsage=new int;
*itsage=*c.itsage;
//itsage=c.itsage;
cout<<*itsage<<" "<<*c.itsage<<endl;
cout<<itsage<<" "<<c.itsage<<endl;
cout<<&itsage<<" "<<&c.itsage<<endl;
}
void Cat::setage(int age)
{
//itsage=new int ;
*itsage=age;
}
Cat::~Cat()
{
delete itsage;
itsage=0;
}
void main()
{
Cat frisky;
cout<<"frisky's age:"<<frisky.getage()<<endl;
cout<<"setting frisky to 6...\n";
frisky.setage(6);
cout<<"creating boots from frisky\n";
Cat boots(frisky);
cout<<"frisky's age:"<<frisky.getage()<<endl;
cout<<"boots'age:"<<boots.getage()<<endl;
cout<<"setting frisky to 7...\n";
frisky.setage(7);
cout<<"frisky's age:"<<frisky.getage()<<endl;
cout<<"boots'age:"<<boots.getage()<<endl;
}
[求助]大家看一下