上海 俄罗斯菜:析构函数用法的问题?(c++)

来源:百度文库 编辑:神马品牌网 时间:2024/05/10 06:37:26
//Cat.h
#include<iostream.h>
#include<string.h>
class Cat
{
public:
int GetAge(){return age;}
float GetWeight(){return weight;}
char *GetColor(){return color;}
void Print(){cout<<"\nage: "<<age<<"\nweight: "<<weight<<"\ncolor: "<<color<<endl;}
Cat(){age=0;weight=0;color=new char[5]; color="None";}
Cat(float w,int a,char *c){weight=w; age=a; color=new char[strlen(c)+1];strcpy(color,c);}
~Cat()
{
cout<<"\n释放堆区color的内存空间中......."<<endl;
delete []color;
cout<<"OK\n"<<endl;
}
private:
float weight;
int age;
char *color;
};

//Out.cpp
#include<iostream.h>
#include"Cat.h"
void main()
{
Cat cat1(11.5,2,"white");
Cat cat2;
cat1.Print();
cat2.Print();
}

这个程序在运行的时候会出错误,但如果把那个cat2去掉的话,运行就是对的,这是什么原因呢?

先谢谢各位朋友帮忙!
如果把~Cat()函数去掉,也可以运行。结果也是对的。

Cat(){age=0;weight=0;color=new char[5]; color="None";}
改成:
Cat(){age=0;weight=0;color=new char[5];strcpy(color,"None");}

不晓得

构造函数Cat()里面color 没有初值,调用的时候没有值