这里的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();
}