1,对于下面的类的声明:
#ifndef PE12_1_H_
#define PE12_1_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;//display all cow data
};
#endif // !PE12_1_H_
给这个类提供实现,并编写一个使用所有成员函数的小程序。
2.通过完成下面的工作来改进 String类声明(即将 Stringl.h升级为 String2.h)。
a.对+运算符进行重载,使之可将两个字符串合并成1个。
b.提供一个 Stinglow()成员函数,将字符串中所有的字母字 符转换为小写(别忘了cctype 系列字符函数)。
c.提供 String()成员函数,将字符串中所有字母字符转换成大写。
d.提供一个这样的成员函数,它接受一个 char参数,返回该字符在字符串中出现的次数。使用下面的程序来测试您的工作:
//pe12-2.cpp
#include<iostream>
using namespace std;
#include "pe12_2.h"
int main()
{
String s1(" and I am a C++ student.");
String s2 = "Please enter your name: ";
String s3;
cout << s2; //overloaded<<operator
cin >> s3; //overloaded >>operator
s2 = "My name is " + s3;//overloaded = ,+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("greed"),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 == rbg[i]) //overloaded == operator
{
cout << "That's right.\n";
success = true;
break;
}
}
if (success)
{
break;
}
else
{
cout << "Try again!\n";
}
}
cout << "Bye\n";
return 0;
}
输出应与下面相似:
Please enter yourname:Fretta Farbo
My name is Fretta Farbo.
The string
MY NAME IS FRETTA FARBO ANDIAMA++ STUDENT.
contains 6’'characters in it.
Enter the name of a primary color for mixing light: yellowTry again!
BLUE
That’s right!
Bye
3.新编写程序清单 10.7和程序清单10.8描述的 Stock 类,使之使用动态分配的内存,而不是 string类对象来存储股票名称。另外,使用重载的operator<<()定义代替show()成员函数。再使用程序清单10.9测试新的定义程序。
正如私有成员表明的,这个类使用动态分配的数组来保存栈项。请重新编写方法,以适应这种新的表
示法,并编写一个程序来演示所有的方法,包括复制构造函数和赋值运算符。