C ++ Primer Plus 第六版 第十二章编程练习答案

1.对于下面的类声明
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; //display all cow data
};

给这个类提供实现,并编写一个使用所有成员函数的小程序。

//main.cpp
#include <iostream>
#include <cstring>
#include"Cow.h"

using std::strcpy;
using std::cin;
using std::cout;
using std::endl;
int main()
{
	Cow milk ( "Fuck", "eat", 56.9 );//Cow::Cow ( const char *nm, const char *ho, double wt )

	Cow junk ( "Shit", "cao", 200.66 );//Cow::Cow ( const char *nm, const char *ho, double wt )

	milk.ShowCow();
	cout << endl;
	Cow m1;//Cow::Cow()
	m1 = milk;//Cow & Cow::operator= ( const Cow & c )
	m1.ShowCow();
	cout << endl;
	Cow m2 = junk;//Cow::Cow ( const Cow & c ),等价于m2(junk)
	m2.ShowCow();
	cout << endl;
	Cow m3;//Cow::Cow()
	m3.ShowCow();
	cout << endl;
	m3=m1=m2;//Cow & Cow::operator= ( const Cow & c )
	m3.ShowCow();
	cout << endl;
	return 0;
}

Cow::Cow()
{
	strcpy ( name, "default" );
	hobby = new char[20];
	hobby="";
	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 )
{
	int len = strlen ( c.hobby );
//没有delete[] hobby,因为这个是构造函数,会调用析构,不用手动delete
	weight = c.weight;
	hobby = new char[len + 1];
	strcpy ( name, c.name );
	strcpy ( hobby, c.hobby );
}

Cow & Cow::operator= ( const Cow & c )
{
	if ( this == &c )
		return *this;
	int len = strlen ( c.hobby );
	delete []hobby;//删除=左边的对象的hobby,因为=左边对象用了默认构造,new了hobby
	weight = c.weight;
	hobby = new char[len + 1];//给hobby开辟一个新空间,不然就会造成浅拷贝,复制地址,析构时会删除两个,导致程序出错
	strcpy ( name, c.name );//name不用new,因为name是char数组,每个对象都有自己的name地址
	strcpy ( hobby, c.hobby );
	return *this;//返回一个副本
}

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

void Cow::ShowCow() const
{
	cout << "name: " << name << endl;
	cout << "hobby: " << hobby << endl;
	cout << "weight: " << weight << endl;
}
//Cow.cpp
#ifndef COW_H_INCLUDED
#define COW_H_INCLUDED

class Cow
{
	char name[20];
	char *hobby;
	double weight;
public:
	Cow();
	Cow ( const char *nm, const char *ho, double wt );
	Cow ( const Cow & );
	~Cow();
	Cow & operator= ( const Cow & );
	void ShowCow() const;
};

#endif // COW_H_INCLUDED

2.通过完成下面的工作来改进String类声明(即将String1.h升级为String2.h)。
a。对+运算符进行重载,使之可将两个字符串合并成1个。
b。提供一个Stringlow()成员函数,将字符串中所有的字母字符转换为小写(别忘了cctype系列字符函数)。
c。提供String()成员函数,将字符串中所有字母字符转换成大写。
d。提供一个这样的成员函数,它接受一个char参数,返回该字符在字符串中出现的字数。
使用下面的程序来测试您的工作:
//pe12_2.cpp
#include<iostream>
using namespace std;
#include"string2.h"
int main()
{
String s1(" and I am a C++ student.");
String s2 = "Please enter your name: ";
String s3;
cout << s2; //overload <<operator
cin >> s3; //overload >>operator
s2 = "My name is " + s3; //overload = , + operators
cout << s2 << ".\n";
s2 = s2 + s1;
s2.stringup(); //converts string to uppercase
cout << "The string\n" << s2 << "\ncontains " << s2.has('A') << " 'A' characters in it.\n";
s1 = "red"; //String (const char *),
//then String & operator= (const String&)
String rgb[3] = { String(s1), String("green"), String("blue")};
cout << "Enter the name of a primary color for mixing light: ";
String ans;
bool success = false;
while (cin >> ans)
{
ans.stringlow(); //converts string to lowercase
for (int i = 0; i < 3; i++)
{
if (ans == rgb[i]) //overload == operator
{
cout << "That's right!\n";
success = true;
break;
}
}
if (success)
break;
else
cout << "Try again!\n";
}
cout << "Bye\n";
return ;
}
输出应与下面相似:
Please enter your name: Fretts Farbo
My name is Fretta Farbo.
The strign
MY NAME ISFRETTA FARBO AND I AM A C++ STUDENT.
contains 6 'A' characters in it.
Enter the name of a primary color for mixing light: yellow
Try again!
BLUE
Tha's right!
Bye

#include <iostream>
#include <cstring>
#include <cctype>

class String
{
private:
	char *str;
	int len;
public:
	String ();
	~String ();
	String ( const char * );
	String operator + ( const String & ) const;
String & operator=(const char * s);
friend String operator + ( const char *, const String & ) ;
friend std::ostream & operator << ( std::ostream &, const String & );
friend std::istream & operator >> ( std::istream &, String & );
void stringlow();
void stringup();
int has ( char letter ) const;
bool operator == ( const String & ) const;
String & operator = ( const String & );
};
String::String ()
{
	len = 0;
	str = new char[1];
	str [0] = '\0';
}
String::~String ()
{
	delete []str;
}
String::String ( const char * c )
{
	len = std::strlen ( c );
	str = new char[len + 1];
	std::strcpy ( str, c );
}
String String::operator + ( const String & s ) const
{
	String temp;
	temp.len = len + s.len;
	delete []temp.str;
	temp.str = new char[temp.len + 1];
	std::strcpy ( temp.str, str );
	std::strcat ( temp.str, s.str );
	return temp;
}
String operator + ( const char * c, const String & s )
{
	String temp;
	delete []temp.str;
	temp.len = std::strlen ( c ) + s.len;
	temp.str = new char[temp.len + 1];
	std::strcpy ( temp.str, c );
	std::strcat ( temp.str, s.str );
	return temp;
}
std::ostream & operator << ( std::ostream & os, const String & s )
{
	os << s.str;
	return os;
}
std::istream & operator >> ( std::istream & in, String & s )
{
  char temp[100];
  in.get(temp,100);
  if(in)
	s=temp;
  while(in&&in.get()!='\n');
  continue;
  return in;


}
String & String::operator=(const char * s)
{
    delete [] str;
    len = std::strlen(s);
    str = new char[len + 1];
    std::strcpy(str, s);
    return *this;
}
/*std::istream & operator >> ( std::istream & in, String & s )
{
	delete []s.str;//因为定义了一隔String对象,使用无参构造,但是无参构造,空间不够,,所以得删除,再重新创立;
	char *t=new char[100];
	in.get(t,100);
	in.get();
	s.len=std::strlen(t);
	s.str=new char[s.len+1];
	strcpy(s.str,t);
	delete []t;
	return in;
}*/
void String::stringlow()
{
	for ( int i = 0; i < len; i++ )
		str[i] = tolower ( str[i] );
}
void String::stringup()
{
	for ( int i = 0; i < len; i++ )
		str[i] = toupper ( str[i] );
}
int String::has ( char letter ) const
{
	int n = 0, i = 0;
	for ( ; i < len; i++ )
		if ( str[i] == 'A' )
			n++;
	return n;
}
bool String::operator == ( const String & s ) const
{
	int  i = 0;
	for ( ; i < len; i++ )
		if ( str[i] != s.str[i] )
			return false;

	return true;
}
String & String::operator = ( const String & s )
{
	delete []str;
	len = std::strlen ( s.str );
	str = new char[len + 1];
	std::strcpy ( str, s.str );
	return *this;
}




int main()
{
	using namespace std;
	String s1 ( " and I am a C++ student." );
	String s2 = "Please enter your name: ";
	String s3;
	cout << s2;   //overload <<operator
	cin >> s3;    //overload >>operator
	s2 = "My name is " + s3;    //overload = , + operators
	cout << s2 << ".\n";
	s2 = s2 + s1;
	s2.stringup();      //converts string to uppercase
	cout << "The string\n" << s2 << "\ncontains " << s2.has ( 'A' ) << " 'A' characters in it.\n";
	s1 = "red";     //String (const char *),
	//then String & operator= (const String&)
	String rgb[3] = { String ( s1 ), String ( "green" ), String ( "blue" ) };
	cout << "Enter the name of a primary color for mixing light: ";
	String ans;
	bool success = false;
	while ( cin >> ans )//记住用while循环,记得清空cin留下的回车换行符, 所以重载里要清楚回车换行符
	{
		ans.stringlow();        //converts string to lowercase
		for ( int i = 0; i < 3; i++ )
		{
			if ( ans == rgb[i] ) //overload == operator
			{
				cout << "That's right!\n";
				success = true;
				break;
			}
		}
		if ( success )
			break;
		else
			cout << "Try again!\n";
	}
	cout << "Bye\n";
	system ( "pause" );
	return 0;
}


3.新编写程序清单10.7和程序清单10.8描述的Stock类,使之使用动态分配的内存,而不是string类对象来存储股票名称。另外,使用重载的perator<<()定义代替show()成员函数。再使用程序清单10.9测试新的定义程序。

#include <iostream>
#include<cstring>
#include "stock.cpp"
#include"stock.h"

const int STKS = 4;

int main()
{
	Stock stocks[STKS] =
	{
		Stock ( "NanoSmart", 12, 20.0 ),
		Stock ( "Boffo Objects", 200, 2.0 ),
		Stock ( "Monolithic Obelisks", 130, 3.25 ),
		Stock ( "Fleep Enterprises", 60, 6.5 )
	};
	std::cout << "Stock holdings:\n";
	int st;
	for ( st = 0; st < STKS; st++ )
		std::cout << stocks[st];
	const Stock *top = &stocks[0];
	for ( st = 1; st < STKS; st++ )
		top = &top->topval ( stocks[st] );
	std::cout << "\nMost valuable holding:\n" << *top;
	std::cout <<ASD;
	return 0;
}
#include <iostream>
#include<cstring>
#include"stock.h"

Stock::Stock()
{
	len = 0;
	company = new char[1];
	company[0] = '\0';
	shares = 0;
	share_val = 0;
	total_val = 0;
}
Stock::~Stock()
{
	delete []company;
}
Stock::Stock ( const char * c, int n, double pr )
{
	len = std::strlen ( c );
	company = new char[len + 1];
	std::strcpy(company,c);
	if ( n < 0 )
	{
		std::cout << "Number of shares can't be negative; "
		          << company << " shares set to 0.\n";
		shares = 0;
	}
	else
		shares = n;
	share_val = pr;
	set_tot();

}
std::ostream & operator << ( std::ostream & os, const Stock & s )
{
	std::ios_base::fmtflags orig = os.setf ( std::ios_base::fixed, std::ios_base::floatfield );
	std::streamsize prec = os.precision ( 3 );
	os << "Company: " << s.company
	   << "  Shares: " <<s. shares << '\n';
	os << "  Share Price: $" << s.share_val;
	os.precision ( 2 );
	os << "  Total Worth: $" <<s. total_val << '\n';
	os.setf ( orig, std::ios_base::floatfield );
	os.precision ( prec );
	return os;
}
const Stock & Stock::topval ( const Stock & s ) const
{
	if(s.total_val>total_val)

	return s;
	else

		return *this;

}



#ifndef STOCK_H_INCLUDED
#define STOCK_H_INCLUDED
class Stock
{

private:
	char *company;
	int len;
	int shares;
	double share_val;
	double total_val;
	void set_tot()
	{
		total_val = shares * share_val;
	}
public:
	const int ASD=5;
	Stock();
	~Stock();
	Stock ( const char *, int n = 0, double pr = 0 );
	friend std::ostream & operator <<(std::ostream & os,const Stock & s) ;
	const Stock & topval(const Stock & s)const;
};

#endif // STOCK_H_INCLUDED


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值