C++ Primer Plus第六版编程练习12.1解答

Cow.h

#ifndef COW_H_
#define COW_H_

class Cow
{
    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

Cow.cpp

#include "Cow.h"
#include <cstring>
#include <iostream>

using std::strcpy;
using std::strlen;

Cow::Cow()
{
    name[0]='\0';
    hobby=new char [1];  //不能用new char,因为与析构函数不对应
    hobby[0]='\0';
    weight=0;
}

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

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

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

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);
    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<<std::endl;
    std::cout<<std::endl;
}

main.cpp

#include "Cow.h"
#include <iostream>

int main()
{
    Cow c1;
    c1.ShowCow();
    Cow c2("zhangzhiping", "basketball", 67);
    c2.ShowCow();
    std::cout<<"Assign one object to another:\n";
    c1=c2;
    c1.ShowCow();
    std::cout<<"Initialize one object to another:\n";
    Cow c3=c2;
    c3.ShowCow();
    std::cout<<"Done!\n";

    std::cin.get();
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值