求问关于C++ 拷贝构造函数 小程序问题?

#include "stdafx.h"
#include "iostream.h"

class CAT
{
int *itsAge;
public:
CAT():itsAge(new int(5)){}
//增加拷贝构造函数
CAT(CAT &c)
{
*itsAge=c.*itsAge;//把c中的itsAge指针指向的内容赋给当前对象的*itsAge
}
~CAT(){ delete itsAge;}
int GetAge() const {return *itsAge;}
void setAge(int age){*itsAge=age;}
};
void main()
{
CAT fri;
cout<<"1111111 "<<fri.GetAge()<<endl;
fri.setAge(6);
CAT boot(fri);
cout<<"1111112 "<<fri.GetAge()<<endl;
cout<<"2222221 "<<boot.GetAge()<<endl;
fri.setAge(7);
cout<<"1111113 "<<fri.GetAge()<<endl;
cout<<"2222222 "<<boot.GetAge()<<endl;
}

程序目的是通过添加拷贝构造函数来使原来的程序正常化。
编译时出错了..希望大家帮忙看看错在哪了...

慕容森
浏览 294回答 2
2回答

万千封印

//#include "stdafx.h"#include "iostream.h"class CAT{int *itsAge;public:CAT():itsAge(new int(5)){}//增加拷贝构造函数CAT(CAT &c){itsAge = new int(0);*itsAge=*c.itsAge;//把c中的itsAge指针指向的内容赋给当前对象的*itsAge}~CAT(){delete itsAge;}int GetAge() const {return *itsAge;}void setAge(int age){*itsAge=age;}};void main(){CAT fri;cout<<"1111111 "<<fri.GetAge()<<endl;fri.setAge(6);CAT boot(fri);cout<<"1111112 "<<fri.GetAge()<<endl;cout<<"2222221 "<<boot.GetAge()<<endl;fri.setAge(7);cout<<"1111113 "<<fri.GetAge()<<endl;cout<<"2222222 "<<boot.GetAge()<<endl;}

Qyouu

//#include"stdafx.h"#include"iostream.h"classCAT{int*itsAge;public:CAT():itsAge(newint(5)){}//增加拷贝构造函数CAT(CAT&c){itsAge=newint(0);*itsAge=*c.itsAge;//把c中的itsAge指针指向的内容赋给当前对象的*itsAge}~CAT(){deleteitsAge;}intGetAge()const{return*itsAge;}voidsetAge(intage){*itsAge=age;}};voidmain(){CATfri;cout<<"1111111"<<fri.GetAge()<<endl;fri.setAge(6);CATboot(fri);cout<<"1111112"<<fri.GetAge()<<endl;cout<<"2222221"<<boot.GetAge()<<endl;fri.setAge(7);cout<<"1111113"<<fri.GetAge()<<endl;cout<<"2222222"<<boot.GetAge()<<endl;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
Python