COW.H
#pragma once
#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;//display all data
};
#endif
function.cpp
#include "COW.h"
//#include <string>
#include <iostream>
Cow::Cow()
{
name[0] = '\0';
hobby = new char[1];
*hobby = '\0';//初始化指针指向内容,不可或缺
weight = 0.0;
}
Cow::~Cow()
{
delete[]hobby;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
strcpy(name, nm);
int len = std::strlen(ho);
hobby = new char[len + 1];
std::strcpy(hobby, ho);
weight = wt;
}
Cow::Cow(const Cow & c)
{
strcpy(name, c.name);
int len = std::strlen(c.hobby);
hobby = new char[len + 1];
std::strcpy(hobby, c.hobby);
weight = c.weight;
}
Cow & Cow::operator=(const Cow & c)
{
strcpy(name, c.name);
if (this == &c)
return *this;
delete[]hobby;
int len = std::strlen(c.hobby);
hobby = new char[ len + 1];
std::strcpy(hobby, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow() const
{
using std::cout;
using std::endl;
cout << "name:" << name << endl;
cout << "hobby:" << hobby << endl;
cout << "weight:" << weight << endl << endl;
}
main.cpp()
#include "COW.h"
#include <iostream>
#include <cstdlib>
int main()
{
Cow co;
Cow wo ("Hello Kity","Jackson Wei",50);
co.ShowCow();
wo.ShowCow();
co = wo;
co.ShowCow();
Cow xo("Mikko", "Sam", 20);
Cow to(xo);
to.ShowCow();
system("pause");
return 0;
}