运行报错
头文件#ifndef COW_H_
#define COW_H_
namespace COW
{
class Cow
{
private:
char name[20];
char* hoppy;
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
源代码1
#include"stack.h"
#include<iostream>
#include<cstring>
namespace COW
{
Cow::Cow()
{
const char* temp = "no date";
hoppy = new char(strlen(temp) + 1);
for (int i = 0; i < strlen(temp)+1 ; i++)
name[i] = hoppy[i] = temp[i];
name[strlen(temp) ] = hoppy[strlen(temp) ] = '\0';
weight = 0;
}
Cow::Cow(const char* nm, const char* ho, double wt)
{
for (int i = 0; i < strlen(nm) + 1; i++)
name[i] = nm[i];
name[strlen(nm) + 1] = '\0';
hoppy = new char(strlen(ho) + 1);
for (int i = 0; i < strlen(ho)+1; i++)
hoppy[i] = ho[i];
hoppy[strlen(ho)] = '\0';
weight = wt;
}
Cow::Cow(const Cow& c)
{
for (int i = 0; i < strlen(c.name); i++)
name[i] = c.name[i];
name[strlen(c.name) + 1] = '\0';
hoppy = new char(strlen(c.hoppy) + 1);
for (int i = 0; i < strlen(c.hoppy)+1; i++)
hoppy[i] = c.hoppy[i];
hoppy[strlen(c.hoppy)] = '\0';
weight = c.weight;
}
Cow::~Cow()
{
std::cout << name << " hoppy:" << hoppy << " object had deleted\n";
delete[]hoppy;
}
Cow& Cow::operator=(const Cow& c)
{
if (this == &c)
return *this;
delete[]hoppy;
for (int i = 0; i < strlen(c.name); i++)
name[i] = c.name[i];
name[strlen(c.name) + 1] = '\0';
hoppy = new char(strlen(c.hoppy) + 1);
for (int i = 0; i < strlen(c.hoppy); i++)
hoppy[i] = c.hoppy[i];
hoppy[strlen(c.hoppy) + 1] = '\0';
weight = c.weight;
}
void Cow::ShowCow()const
{
std::cout << "Name:" << name << std::endl;
std::cout << "Hoppy:" << hoppy << std::endl;
std::cout << "Weight:" << weight << std::endl;
}
}
源代码2
#include<iostream>
#include"stack.h"
int main()
{
{
using std::cout;
using std::cin;
using std::endl;
using COW::Cow;
Cow st1;
Cow st2("chen", "music", 60);
Cow st3 = st2;
st1.ShowCow();
st2.ShowCow();
st3.ShowCow();
}
std::cout << "Done!\n";
return 0;
}
我想的是最后结束后
显示:
chen music objected had deleted
chen music objected had deleted
no data no data objected had deleted
Done!