#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
#include "Cow.h"
#include <iostream>
using std::cout;
using std::endl;
Cow::Cow()
{
strcpy_s(name, 20, "Default");
hobby = new char[20];
strcpy_s(hobby, 20, "Default Hobby");
weight = 0;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
strcpy_s(name, 20, nm);
hobby = new char(strlen(ho)+1);
strcpy_s(hobby, strlen(ho) + 1, ho);
weight = wt;
}
Cow::Cow(const Cow & c)
{
strcpy_s(name, 20, c.name);
hobby = new char(strlen(c.hobby)+1);
strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
delete[]hobby;
}
Cow & Cow::operator=(const Cow & c)
{
if (this == &c)
return *this;
delete[]hobby;
strcpy_s(name,20, c.name);
hobby = new char(strlen(c.hobby)+1);
strcpy_s(hobby,strlen(c.hobby)+1, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow() const
{
cout << "The name: " << name << " , and the hobby: " << hobby << " , and the weight: "
<< weight << endl;
}
#include <iostream>
#include "Cow.h"
using std::cout;
using std::endl;
int main()
{
{
Cow t1;
cout << "The first Cow object:\n";
t1.ShowCow();
Cow t2("mark", "football", 120);
cout << "The second Cow object:\n";
t2.ShowCow();
Cow t3(t1);
cout << "The third Cow object (copy by the first one):\n";
t3.ShowCow();
Cow t4 = t2;
cout << "The fourth Cow object update:\n";
t4.ShowCow();
}
return 0;
}
1 回答
- 1 回答
- 0 关注
- 5479 浏览
添加回答
举报
0/150
提交
取消