大家能否帮我把这个关于赋值运算符的程序填写完整???

xiaoshahui1 2004-05-05 09:30:16
以下这个程序是我从书上抄来的,为了节省内存取消了复制构造函数和析构函数,
因为我是一个初学者,所以我很想看看完整的程序什么样子的,还烦请大家帮我
把复制构造函数和析构函数添上去,谢谢!!!
#include <iostream>
using namespace std;

class CAT
{
public:
CAT();
int GetAge() const { return *itsAge;}
int GetWeight() const { return *itsWeight;}
void SetAge(int age) { *itsAge=age;}
CAT &operator=(const CAT &);
private:
int *itsAge;
int *itsWeight;
};


CAT::CAT()
{
itsAge=new int;
itsWeight=new int;
*itsAge=5;
*itsWeight=9;
}


CAT &CAT::operator=(const CAT & rhs)
{
if(this==&rhs)
return *this;
*itsAge=rhs.GetAge();
*itsWeight=rhs.GetWeight();
return *this;
}


int main()
{
CAT frisky;
cout<<"frisky's age: "<<frisky.GetAge()<<endl;
cout<<"Setting frisky to 6...\n";
frisky.SetAge(6);
CAT whiskers;
cout<<"whisker' age: "<<whiskers.GetAge()<<endl;
cout<<"copying frisky to whiskers...\n";
whiskers=frisky;
cout<<"whiskers' age: "<<whiskers.GetAge()<<endl;
return 0;
}
...全文
18 3 点赞 打赏 收藏 举报
写回复
3 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
freefalcon 2004-05-06
太惭愧了,居然忘了申请空间,呵呵
  • 打赏
  • 举报
回复
runall 2004-05-06
CAT &CAT::operator=(const CAT & rhs)
{
if(this==&rhs)
return *this;
*itsAge=rhs.GetAge();
*itsWeight=rhs.GetWeight();
return *this;
}
改为
CAT &CAT::operator=(const CAT & rhs)
{
if(this==&rhs)
return *this;

delete itsAge;
delete itsWeight;

itsAge = new int;
itsWeight = new int;

*itsAge=rhs.GetAge();
*itsWeight=rhs.GetWeight();
return *this;
}


CAT::CAT(const CAT& rhs);
{
*itsAge=rhs.GetAge(); //或*itsAge=*rhs.itsAge;下同
*itsWeight=rhs.GetWeight();
}
改为
CAT::CAT(const CAT& rhs);
{
itsAge = new int;
itsWeight = new int;

*itsAge=rhs.GetAge(); //或*itsAge=*rhs.itsAge;下同
*itsWeight=rhs.GetWeight();
}


  • 打赏
  • 举报
回复
freefalcon 2004-05-05
class CAT
{
public:
CAT(const CAT& rhs);
~CAT();
};

CAT::CAT(const CAT& rhs);
{
*itsAge=rhs.GetAge(); //或*itsAge=*rhs.itsAge;下同
*itsWeight=rhs.GetWeight();
}

CAT::~CAT()
{
delete itsAge;
delete itsWeight;
}
  • 打赏
  • 举报
回复
相关推荐
发帖
C++ 语言
加入

6.0w+

社区成员

C++ 语言相关问题讨论,技术干货分享,前沿动态等
申请成为版主
帖子事件
创建了帖子
2004-05-05 09:30
社区公告
暂无公告