现在的位置: 首页 > 综合 > 正文

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

2014年10月15日 ⁄ 综合 ⁄ 共 1446字 ⁄ 字号 评论关闭

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();


}

抱歉!评论已关闭.