#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 <iostream>
#include <cstring>
#include "cow.h"
#pragma warning(disable:4996)
Cow::Cow()
{
name[0] = '\0';
hobby = new char[1];
hobby[0] = '\0';
weight = 0;
}
Cow::Cow(const char* nm, const char* ho, double wt)
{
strcpy(name, nm);
int len;
len = std::strlen(ho);
hobby = new char[len + 1];
strcpy(hobby, ho);
weight = wt;
}
Cow::Cow(const Cow& c)
{
std::strcpy(name, c.name);
int len;
len = std::strlen(c.hobby);
hobby = new char[len + 1];
weight = c.weight;
}
Cow::~Cow()
{
delete[] hobby;
std::cout << "byb!\n";
}
Cow& Cow::operator=(const Cow& c)
{
int len;
if (this == &c)
return *this;
delete[] hobby;
weight = c.weight;
len = std::strlen(c.name);
hobby = new char[len + 1];
std::strcpy(hobby, c.hobby);
std::strcpy(name, c.name);
return *this;
}
void Cow::ShowCow() const
{
std::cout << "name: " << name << std::endl;
std::cout << "hobby: " << hobby << std::endl;
std::cout << "weight: " << weight << std::endl;
}
#include <iostream>
#include <cstring>
#include <string>
#include "cow.h"
int main()
{
using std::cout;
using std::endl;
Cow hand1;
hand1.ShowCow();
Cow hand2("chen kai1", "programmer", 200.34);
hand2.ShowCow();
Cow hand3("wang s", "a dan b", 170.72);
hand3.ShowCow();
cout << "transler; \n";
hand2=hand3;
hand2.ShowCow();
hand3.ShowCow();
return 0;
}