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

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;
}
...全文
33 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
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;
}

64,681

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧