#pragma once
class cow
{
char name[20];
char*hobby;
double weight;
public:
cow();
cow(const char*m, const char*ho, double wt);
cow(const cow&c);
cow &operator=(const cow&c);
void showcow()const;
~cow();
};
```cpp
#include "cow.h"
#include<cstring>
#include<iostream>
cow::cow()
{
name[0] = '\0';
hobby = new char[1];
hobby[0] = '\0';
weight = 0;
}
cow::cow(const char*m, const char*ho, double wt)
{
strcpy_s(name, m);
hobby = new char[std::strlen(ho)+1];
strcpy_s(hobby, std::strlen(ho) + 1,ho);
weight = wt;
}
cow::cow(const cow&c)
{
strcpy_s(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy_s(hobby, std::strlen(c.hobby) + 1, c.hobby);
weight = c.weight;
}
cow &cow:: operator=(const cow&c)
{
if (this == &c)
return *this;
delete[]hobby;
strcpy_s(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy_s(hobby, std::strlen(c.hobby) + 1, c.hobby);
weight = c.weight;
return *this;
}
void cow::showcow()const
{
std::cout << "name:" << name << std::endl;
std::cout << "hobby:" << hobby << std::endl;
std::cout << "weight:" << weight;
}
cow::~cow()
{
delete[]hobby;
}
```cpp
//实现文件
#include <iostream>
#include <cstring>
#include <string>
#include "cow.h"
int main()
{
using std::endl;
cow a;
a.showcow();
cow b("Bibl", "eat", 207.84);
b.showcow();
cow d(b);
d.showcow();
cow c("selfidh", "dance", 100.42);
c.showcow();
a = c;
a.showcow();
system("PAUSE");
return 0;
}