C++PrimerPlus第六版第十二章类和动态内存分配编程练习答案

本篇博客包含了C++ Primer Plus第六版第十二章关于类和动态内存分配的编程练习解答,包括Cow.h、String.h、Stock.h、Stack.h和Queue.h的相关实现及主函数main.cpp的应用。
摘要由CSDN通过智能技术生成

1.

Cow.h

#ifndef Cow_H_
#define Cow_H_
#include<iostream>
using std::cout;
using std::endl;
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;
};
Cow::Cow()
{
   
	strcpy_s(name, 20, "helloWorld!");
	hobby = nullptr;
	weight = 0.0;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
   
	strcpy_s(name,20,nm);
	int len = strlen(ho);
	hobby = new char[len + 1];
	strcpy_s(hobby, len + 1,ho);
	weight = wt;


}
Cow::Cow(const Cow & c)
{
   
	strcpy_s(name, 20,c.name);
	int len = strlen(c.hobby);
	hobby = new char[len + 1];
	strcpy_s(hobby, len + 1, c.hobby);
	weight = c.weight;
}
Cow::~Cow()
{
   
	delete[]hobby;
}
Cow & Cow::operator = (const Cow & c)
{
   
	if (this == &c)
	{
   
		return *this;
	}
	delete[] hobby;
	strcpy_s(name,20, c.name);
	int len = strlen(c.hobby);
	hobby = new char[len + 1];
	strcpy_s(hobby, len + 1, c.hobby);
	weight = c.weight;
	return  *this;
}
void Cow::ShowCow() const
{
   
	cout << "name: " << name << '\n'
		<< "hobby: " << hobby << '\n'
		<< "weight: " << weight << endl;
}
#endif // Cow_H_

main.cpp

#include "Cow.h"

int main()
{
   
	Cow a;
	Cow b("jack", "study", 120);
	b.ShowCow();
	a = b;
	a.ShowCow();
	Cow c(a);
	c.ShowCow();
	return 0;
}

2.

String.h

#ifndef STRING2_H_H
#define STRING2_H_H

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using std::ostream;
using std::istream;
class String
{
   
private:
	char * str;
	int len;
	static int num_strings;
	static const int CINLIM = 80;
public:

	String(const char *s);
	String();
	String(const String &);
	~String();
	int length()const {
    return len; }

	String & operator= (const String &);
	String & operator= (const char *);
	char & operator[] (int i);
	const char & operator[](int i) const;
	friend bool operator<(const String & st, const String &st2);
	friend bool operator>(const String & st, const String &st2);
	friend bool operator==(const String & st, const String &st2);
	friend ostream & operator<<(ostream & os, const String & st);
	friend istream & operator>>(istream & is, String & st);
	static int Howmany();


	friend String operator+(const char * s, const String & st);
	friend String operator+(const String & st, const String &st1);


	void stringlow();
	void stringup();
	int count(char);
};

int String::num_strings = 0;
int String::Howmany()
{
   
	return num_strings;
}
String::String(const char *s)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值