C++PrimePlus(第六版)第十二章课后编程练习

1小牛
题目看错把第二题的代码也写了!

/******************Cow.h*******************/
#pragma once
#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;
	//friends
	Cow &operator+(const Cow &c);
	void Stringlow();
	void Stringupp();
	int String_num(char c)const;
};
#endif // !COW_H_
/******************Cow.cpp*******************/
#include<iostream>
#include"Cow.h"
#include<string>
using std::cout;
using std::endl;

Cow::Cow()
{
	name[0] = '\0';
	hobby = NULL;
	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()
{
	delete[]hobby;
}

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

void Cow::ShowCow()const
{
	cout << name << endl;
	cout << hobby << endl;
	cout << weight<<endl;
}
Cow &Cow::operator+(const Cow &c)
{
	
	strcat(name, c.name);
	return *this;
}

void Cow::Stringlow()
{
	int i, len;
	len = strlen(name);
	for(i=0;i<len;i++)
	{
		if (name[i] >= 65 && name[i] <= 90)
			name[i]=name[i] + 32;
	}
}
void Cow::Stringupp()
{
	int i, len;
	len = strlen(name);
	for (i = 0; i < len; i++)
	{
		if (name[i] >= 97 && name[i] <= 122)
			name[i]=name[i] - 32;
	}
}
int Cow::String_num(char c)const
{
	int i, len,num=0;
	len = strlen(name);
	for (i = 0; i < len; i++)
	{
		if (name[i] ==c)
			num++;
	}
	return num;
}
#include<iostream>
#include"Cow.h"
using std::cout;
using std::endl;
using std::cin;

int main()
{
	int n;
	Cow petter,piss;
	Cow jack("jackchen", "footbal", 100);
	Cow xiaoli("CHONGZheng", "sleeping", 200);
	Cow laoli("AAABBBCCCdddeeeeAA", "sleeping", 200);
	petter = jack;
	jack.ShowCow();
	piss=jack + xiaoli;
	cout << "piss string" << endl;
	piss.ShowCow();
	xiaoli.ShowCow();
	xiaoli.Stringlow();
	xiaoli.ShowCow();
	n=laoli.String_num('A');
	cout << n << endl;
	//system("PAUSE");
	return 0;
}
发布了8 篇原创文章 · 获赞 49 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44735475/article/details/104346494