用operator<<( )方法输出有new动态分配的类对象时造成程序的终止运行问题?
//头文件#ifndef COW_H_
#define COW_H_
#include<iostream>
using std::ostream;
using std::istream;
class Cow
{
char name[20];
char * hobby;
double weight;
int len;
public:
Cow();
Cow(const char * nm,const char * ho,double wt);
Cow(const Cow & c);
~Cow();
Cow & operator=(const Cow & c);
//Cow & operator=(const char * c);
void ShowCow()const;
friend ostream & operator<<(ostream & os,const Cow t);
};
#endif
//源文件
#include<iostream>
#include"cow.h"
Cow::Cow()
{
hobby=new char[1];
hobby[0]='\0';
strcpy(name,"no name");
weight=0;
}
Cow::Cow(const char * nm,const char * ho,double wt)
{
strncpy(name,nm,20);
name[20]='\0';
len=strlen(ho);
hobby=new char[len+1];
strcpy(hobby,ho);
weight=wt;
}
Cow::Cow(const Cow & c)
{
strcpy(name,c.name);
len=c.len;
hobby=new char[len+1];
strcpy(hobby,c.hobby);
weight=c.weight;
}
Cow::~Cow()
{
delete [] hobby;
}
Cow & Cow::operator=(const Cow & c)
{
if(this==&c)
return *this;
delete [] hobby;
len=c.len;
hobby=new char[len+1];
strcpy(name,c.name);
strcpy(hobby,c.hobby);
weight=c.weight;
return *this;
}
void Cow::ShowCow()const
{
using std::cout;
using std::endl;
cout<<"Name is: "<<name<<" ,hobby is: "<<hobby<<" ,weight is: "<<weight<<endl;
}
ostream & operator<<(ostream & os,const Cow t)
{
using std::cout;
using std::endl;
cout<<"Name is: "<<t.name<<" ,hobby is: "<<t.hobby<<" ,weight is: "<<t.weight<<endl;
return os;
}
//mian()
#include<iostream>
#include"cow.h"
int main()
{
using std::cout;
Cow nu1("xiaoxiaoqiang","baoyuan",50);
Cow nu2;
Cow temp;
// nu1.ShowCow();
cout<<nu1;
// nu2.ShowCow();
cout<<nu2;
nu2=nu1;
// nu2.ShowCow();
cout<<nu2;
return 0;
}
我的问题是为什么用cout<<nu1输出会造成程序的终止,我的深度复制构造函数和析构函数都写了啊,如果我把main()改成用ShowCow输出则没有问题,请问这个是怎么回事啊,我做了好几道关于new动态分配类中字符串的题都遇到了这个问题,我很想知道到底是什么问题,大侠们帮帮我啊~!
#include<iostream>
#include"cow.h"
int main()
{
using std::cout;
Cow nu1("xiaoxiaoqiang","baoyuan",50);
Cow nu2;
Cow temp;
nu1.ShowCow();
// cout<<nu1;
nu2.ShowCow();
// cout<<nu2;
nu2=nu1;
nu2.ShowCow();
// cout<<nu2;
return 0;
}
下面是我用VC6.0创好了的工程,大家直接点击121Cow.dsw运行看看帮我找找问题,感激不尽啊~
121Cow.rar
(852.27 KB)
[[it] 本帖最后由 沿途有鬼 于 2008-8-12 16:23 编辑 [/it]]