c++primer plus第六版第十二章第一题

//h文件
#pragma once
class cow
{
	char name[20];
	char*hobby;
	double weight;
public:
	cow();
	cow(const char*m, const char*ho, double wt);
	cow(const cow&c);
	cow &operator=(const cow&c);
	void showcow()const;
	~cow();
};

```cpp
//类文件
#include "cow.h"
#include<cstring>
#include<iostream>


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

}
cow::cow(const char*m, const char*ho, double wt)
{
	
	strcpy_s(name, m);
	hobby = new char[std::strlen(ho)+1];
	strcpy_s(hobby, std::strlen(ho) + 1,ho);
	weight = wt;


}
cow::cow(const cow&c)
{

	strcpy_s(name, c.name);
	hobby = new char[strlen(c.hobby) + 1];
	strcpy_s(hobby, std::strlen(c.hobby) + 1, c.hobby);
	weight = c.weight;



}
cow  &cow:: operator=(const cow&c)
{
	if (this == &c)
		return *this;
	delete[]hobby;
	strcpy_s(name, c.name);
	hobby = new char[strlen(c.hobby) + 1];
	strcpy_s(hobby, std::strlen(c.hobby) + 1, 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;

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


```cpp
//实现文件
#include <iostream>
#include <cstring>
#include <string>
#include "cow.h"

int main()
{

	using std::endl;
	cow a;
	a.showcow();
	cow b("Bibl", "eat", 207.84);
	b.showcow();
	cow d(b);
	d.showcow();
	cow c("selfidh", "dance", 100.42);
	c.showcow();
	a = c;
	a.showcow();

	system("PAUSE");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值