c++十二章第一题

#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) //这里是关键,没有的话会出现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);   //4996
    int len;
    len = std::strlen(ho);
    hobby = new char[len + 1];
    strcpy(hobby, ho);  //4996
    weight = wt;
}
Cow::Cow(const Cow& c)
{
    std::strcpy(name, c.name);//4996
    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);  //4996
    std::strcpy(name, c.name);  //4996
    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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值