Chapter 12 homework

12.1

#include "cow.h"
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;

Cow::Cow()
{
    name[0] = '\0';
    hobby = new char[1];
    hobby[0] = '\0';
    weight = 0.0;
}

Cow::Cow(const char * nm, const char * ho, double wt): weight(wt)
{
    strcpy(name, nm);
    hobby = new char[strlen(ho) + 1];
    strcpy(hobby, ho);
}

Cow::~Cow()
{
    delete [] hobby;
}

// copy constructor
Cow::Cow(const Cow &c)
{
    strcpy(name, c.name);
    hobby = new char[strlen(hobby)+1];
    strcpy(hobby, c.hobby);
    weight = c.weight;
}

Cow & Cow::operator=(const Cow & c)
{
    if(this == &c)
        return *this;
    delete [] hobby;
    strcpy(name, c.name);
    hobby = new char[strlen(c.hobby)+1];
    strcpy(hobby, c.hobby);
    return *this;
}

void Cow::ShowCow() const
{
    cout << "Name: " << name << '\t' << "Hobby: " << hobby << '\t';
    cout << "Weight: " << weight << endl;
}
cow.cpp

 

posted @ 2018-03-28 15:12  Bear_Guo  阅读(98)  评论(0编辑  收藏  举报