您的位置:首页 > 编程语言 > C语言/C++

C++primer plus第六版课后编程题答案12.1

2014-04-19 23:42 465 查看
这里的delete[]应该改一下,改为delete,delete[]是对类似数组这种对象使用的,会对数组里面的每个对象调用一次析构函数,而delete则是对单个对象使用的。

-----------------2014.10.28

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Cow.h

#ifndef COW_h_
#define COW_h_
class Cow{
private:
char name[20];
char *hobby;
double weight;
public:
Cow();
Cow(const char *nm,const char *ho,double wt);
Cow(const Cow &c);
~Cow();
Cow &operator=(const Cow &c);
void showCow()const;

};

#endif


Cow.cpp

#include <iostream>
#include "Cow.h"
//#include <string>
#include <cctype>
using namespace std;
const int LIMIT=20;
Cow::Cow()
{
strcpy(name,"default");//居然把strcpy写成了strcmp,我去啊
hobby=new char[LIMIT];//remember delete[]
strcpy(hobby,"defaulthobby");
weight=0;
cout<<"Cow() creat!"<<endl;
}
Cow::Cow(const char *nm,const char *ho,double wt)
{
//cout<<"first name is "<<name<<endl;
strcpy(name,nm);
//cout<<"now name is "<<name<<endl;
hobby=new char[LIMIT];//remember delete[]
//char *hobby=new char[LIMIT];//remember delete[]
strcpy(hobby,ho);
weight=wt;
cout<<"Cow(const,const,wt) creat!"<<endl;
}
Cow::Cow(const Cow &c)
{
strcpy(name,c.name);
hobby=new char[LIMIT];
strcpy(hobby,c.hobby);
weight=c.weight;
cout<<"Cow(Cow&) creat!"<<endl;
}
Cow::~Cow()
{
delete[]hobby;
cout<<"Cow() destroy!"<<endl;
}
Cow& Cow::operator=(const Cow &c)
{
strcpy(name,c.name);
delete []hobby;//记得删掉原来的
char *hobby=new char[LIMIT];
strcpy(hobby,c.hobby);
weight=c.weight;
return Cow(name,hobby,weight);//为何不能返回this??
}
void Cow::showCow()const
{
cout<<"name:"<<name<<endl;
cout<<"hobby:"<<hobby<<endl;
cout<<"weight:"<<weight<<endl<<endl;
}


main121.cpp

#include <iostream>
#include "Cow.h"
using namespace std;
void main121()
{
{
Cow c1;
c1.showCow();
Cow c2("wawa","eat glassess",150);
c2.showCow();
Cow c3=c2;
c3.showCow();
Cow c4(c2);
c4.showCow();

}

cin.get();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息