【#文档大全网# 导语】以下是®文档大全网的小编为您整理的《C 面向对象程序设计习题解答与上机指导(第二版)源程序》,欢迎阅读! C++面向对象程序设计习题解答与上机指导(第2版) 习题参考答案源代码 使用源程序的几点注意事项 (1) 由于源程序在复制、编辑、解压缩等过程中可能引起部分符号(主要是标点符号,如分号、冒号、逗号、引号)的字体、半全角等发生变化,在编译时可能被检出语法错误,只要使用“替换”功能,纠正后即能顺利运行。 (2) 有的C++系统(如Visual C++6.0)没有完全实现C++标准,它所提供的不带后缀的.h的头文件不支持友元运算符重载函数,在Visual C++6.0中编译会出错,这时可采用带后缀的.h头文件。将程序中的 #include using namespace std。 修改成 #include 即可顺利运行。 第2章 C++基础 【2.2】下面是一个C程序,改写它,使它采用C++风格的I/O语句。 #include int main() { int a,b,d,min。 printf("Enter two numbers:")。 scanf("%d%d",&a,&b)。 min=a>b? b:a。 for (d=2。 d。 d++) if (((a%d)==0)&&((b%d)==0)) break。 if (d==min) { printf("No common denominators\n")。 return 0。 } printf("The lowest common denominator is %d\n",d)。 return 0。 } 【解】 #include using namespace std。 int main() { int a,b,d,min。 cout<<"Enter two numbers:"。 1 / 72 cin>>a。 cin>>b。 min=a>b? b:a。 for (d=2。 d。 d++) if (((a%d)==0)&&((b%d)==0)) break。 if (d==min) { cout<<"No common denominators\n"。 return 0。 } cout<<"The lowest common denominator is "<。 return 0。 } 【2.24】写出下列程序的运行结果。 #include using namespace std。 int i=15。 int main() { int i。 i=100。 ::i=i+1。 cout<<::i<。 return 0。 } 运行结果:101 Please any key to continue。 【2.25】写出下列程序的运行结果。 #include using namespace std。 void f(int &m,int n) { int temp。 temp=m。 m=n。 n=temp。 } int main() { int a=5,b=10。 f(a,b)。 cout<。 return 0。 } 结果:10 10 Please any key to continue。 【2.26】分析下面程序的输出结果。 2 / 72 #include using namespace std。 int &f(int &i) {i+=10。 return i。 } int main() {int k=0。 int &m=f(k)。 cout<。 m=20。 cout<。 return 0。 } 运行结果:10 20 Please any key to continue。 【2.27】编写一个C++风格的程序,用动态分配空间的方法计算Fibonacci数列的前20项并存储到动态分配的空间中。 【解】实现本题功能的程序如下: #include using namespace std。 int main() { int *p=new int[20]。 //动态分配20个整型内存空间 *p=1。 *(p+1)=1。 //对前面2个内存空间赋值1 cout<<*p<<"\t"<<*(p+1)<<"\t"。 p=p+2。 //p指向第3个内存空间 for (int i=3。i<=20。i++) { *p=*(p-1)+*(p-2)。 cout<<*p<<"\t"。 if (i%5==0) cout<。 p++。 //p指向下一个内存空间。 } return 0。 } 【2.28】编写一个C++风格的程序,建立一个被称为sroot的函数,返回其参数的二次方根。重载函数sroot三次,让它返回整数、长整数与双精度数的二次方根(计算二次方根时,可以使用标准库函数sqrt)。 【解】实现本题功能的程序如下: #include #include using namespace std。 3 / 72 double sroot(int i) { return sqrt(i)。 } double sroot(long l) { return sqrt(l)。 } double sroot(double d) { return sqrt(d)。 } int main() { int i=12。 long l=1234。 double d=12.34。 cout<<"i的二次方根是:"<。 cout<<"l的二次方根是:"<。 cout<<"d的二次方根是:"<。 return 0。 } 【2.29】编写一个C++风格的程序,解决百钱问题:将一元人民币兑换成1、2、5分的硬币,有多少种换法? 【解】实现本题功能的程序如下: #include using namespace std。 int main() { int i,j,sum=0。。 for(i=0。i<=20。i++) for (j=0。j<=50。j++) if (100-5*i-2*j>=0) { sum++。 cout<<100-5*i-2*j<<"\t"<。 } cout<<"sum is "<。 return 0。 } 【2.30】编写一个C++风格的程序,输入两个整数,将它们按由小到大的顺序输出。要求使用变量的引用。 【解】实现本题功能的程序如下: #include using namespace std。 int main() { void change(int &,int &)。 int a,b。 cin>>a>>b。 if(a>b)change(a,b)。 4 / 72 cout<。 return 0。 } void change(int &a1,int &b1) {int temp。 temp=a1。 a1=b1。 b1=temp。 } 【2.31】编写C++风格的程序,用二分法求解f(x)=0的根。 【解】实现本题功能的程序如下: #include #include using namespace std。 inline float f(float x) { return 2*x*x*x-4*x*x+3*x-6。 } int main() { float left,right,middle,ym,yl,yr。 cout<<"please two number:"<。 //接收输入,确定第一组数据区域 cin>>left>>right。 yl=f(left)。 yr=f(right)。 do { middle=(right+left)/2。 ym=f(middle)。 if (yr*ym>0) { right=middle。 yr=ym。 } else { left=middle。 yl=ym。 } } while (fabs(ym)>=1e-6)。 cout<<"\nRoot is :"<。 return 0。 } 第3章 类和对象(一) 【3.18】写出下面程序的运行结果。 #include using namespace std。 5 / 72 class test {public: test() 。 ~test(){ }。 private: int i。 }。 test::test() {i = 25。 for (int ctr=0。 ctr<10。 ctr++) { cout<<"Counting at "<。 } } test anObject。 int main() { return 0。 } 【3.19】写出下面程序的运行结果。 #include using namespace std。 class Test{ private: int val。 public: Test() {cout<<"default."<。 } Test(int n) {val=n。 cout<<"Con."<。 } Test(const Test& t) {val=t.val。 cout<<"Copy con."<。 } }。 int main() {Test t1(6)。 Test t2=t1。 Test t3。 t3=t1。 return 0。 } 【3.20】指出下列程序中的错误,并说明为什么。 6 / 72 #include using namespace std。 class Student{ public: void printStu()。 private: char name[10]。 int age。 float aver。 }。 int main() { Student p1,p2,p3。 p1.age =30。 … return 0。 } 【3.21】指出下列程序中的错误,并说明为什么。 #include using namespace std。 class Student{ int sno。 int age。 void printStu()。 void setSno(int d)。 }。 void printStu() { cout<<"\nSno is "<。 cout<<"age is "<。 } void setSno(int s) { sno=s。 } void setAge(int a) { age=a。 } int main() { Student lin。 lin.setSno(20021)。 lin.setAge(20)。 lin.printStu()。 } 【3.22】指出下列程序中的错误,并说明为什么。 #include using namespace std。 7 / 72 class Point{ public: int x,y。 private: Point() { x=1。 y=2。 } }。 int main() { Point cpoint。 cpoint.x=2。 return 0。 } 【3.23】下面是一个计算器类的定义,请完成该类成员函数的实现。 class counter{ public: counter(int number)。 void increment()。 //给原值加1 void decrement()。 //给原值减1 int getvalue()。 //取得计数器值 int print()。 //显示计数 private: int value。 }。 【解】 class counter{ public: counter(int number)。 void increment()。 //给原值加1 void decrement()。 //给原值减1 int getvalue()。 //取得计数器值 int print()。 //显示计数 private: int value。 }。 counter::counter(int number) { value=number。 } void counter::increment() { value++。 } void counter::decrement() { value--。 } 8 / 72 int counter::getvalue() { return value。 } int counter::print() { cout<<"value is "<。 return 0。 } 【3.24】根据注释语句的提示,实现类Date的成员函数。 #include using namespace std。 class Date { public: void printDate()。 //显示日期 void setDay(int d)。 //设置日的值 void setMonth(int m)。 //设置月的值 void setYear(int y)。 //设置年的值 private: int day,month,year。 }。 int main() { Date testDay。 testDay.setDay(5)。 testDay.setMonth(10)。 testDay.setYear(2003)。 testDay.printDate()。 return 0。 } 【解】 void Date::printDate() { cout<<"\nDate is "<。 cout<。 } void Date::setDay(int d) { day=d。 } void Date::setMonth(int m) { month=m。 } void Date::setYear(int y) { year=y。 } 【3.25】建立类cylinder,cylinder的构造函数被传递了两个double值,分别表示圆柱体的半径和高度。用类cylinder计算圆柱体的体积,并存储在一个double变量中。在类cylinder中包含一个成员函数vol,用来显示每个cylinder对象的体积。 9 / 72 【解】实现本题功能的程序如下: #include using namespace std。 class cylinder{ public: cylinder(double a,double b)。 void vol()。 private: double r,h。 double volume。 }。 cylinder::cylinder(double a,double b) { r=a。 h=b。 volume=3.141592*r*r*h。 } void cylinder::vol() { cout<<"volume is:"<。 } int main() { cylinder x(2.2,8.09)。 x.vol()。 return 0。 } 【3.26】构建一个类Stock,含字符数组stockcode[]及整型数据成员quan、双精度型数据成员price。构造函数含3个参数:字符数组na[]及q、p。当定义Stock的类对象时,将对象的第1个字符串参数赋给数据成员stockcode,第2和第3个参数分别赋给quan、price。未设置第2和第3个参数时,quan的值为1000,price的值为8.98。成员函数 print没有形参,需使用this指针,显示对象数据成员的内容。假设类Stoc第1个对象的三个参数分别为:"600001", 3000和 5.67 ,第2个对象的第1个数据成员的值是"600001",第2和3数据成员的值取默认值。要求编写程序分别显示这两个对象数据成员的值。 【解】 实现本题功能的程序如下: #include using namespace std。 const int SIZE=80。 class Stock{ public: Stock() { strcpy(stockcode," ")。 } Stock(char code[], int q=1000, double p=8.98) { strcpy(stockcode, code)。 quan=q。 price= p。 10 / 72 } void print(void) { cout<stockcode。 cout<<" "<quan<<" "<price<。 } private: char stockcode[SIZE]。 int quan。 double price。 }。 int main() { Stock st1("600001",3000,5.67)。 st1.print()。 Stock st2("600002")。 st2.print()。 return 0。 } 第4章 类和对象(二) 【4.12】以下程序的运行结果是( )。 #include using namespace std。 class B { public: B(){} B(int i,int j) { x=i。 y=j。 } void printb() {cout<。 } private: int x,y。 }。 class A{ public: A() {} A(int I,int j)。 void printa()。 private: 11 / 72 B c。 }。 A::A(int i,int j):c(i,j) { } void A::printa() {c.printb()。 } int main() { A a(7,8)。 a.printa()。 return 0。 } A) 8,9 B)7,8 C) 5,6 D)9,10 【4.13】以下程序的运行结果是( )。 #include using namespace std。 class A{ public: void set(int i,int j) { x=i。 y=j。 } int get_y() {return y。 } private: int x,y。 }。 class box{ public: void set(int l,int w,int s,int p) { length=l。 width=w。 label.set(s,p)。 } int get_area() {return length*width。 } private: int length,width。 A label。 }。 int main() 12 / 72 { box b。 b.set(4,6,1,20)。 cout<。 return 0。 } A) 24 B) 4 C) 20 D) 6 【4.14】以下程序的运行结果是( )。 #include using namespace std。 class Sample{ public: Sample(int i,int j) { x=i。 y=j。 } void disp() {cout<<"disp1"<。 } void disp() const {cout<<"disp2"<。 } private: int x,y。 }。 int main() { const Sample a(1,2)。 a.disp()。 return 0。 } A) disp1 B) disp2 C) disp1 disp2 D) 程序编译出错 【4.15】以下程序的运行结果是( )。 #include using namespace std。 class R{ public: R(int r1,int r2) { R1=r1。 R2=r2。 } void print()。 void print() const。 private: 13 / 72 int R1,R2。 }。 void R::print() {cout<。 } void R::print() const {cout<。 } int main() { R a(6,8)。 const R b(56,88)。 b.print()。 return 0。 } A) 6,8 B) 56,88 C) 0,0 D) 8,6 【4.16】指出下面程序中的错误,并说明原因。 #include using namespace std。 class Student{ public: Student() { ++x。 cout<<"\nplease input student No."。 cin>>Sno。 } static int get_x() { return x。 } int get_Sno() { return Sno。 } private: static int x。 int Sno。 }。 int Student::x=0。 int main() { cout <。 Student stu1。 Student *pstu=new Student。 cout <。 cout <。 return 0。 14 / 72 } 【4.17】指出下面程序中的错误,并说明原因。 #include using namespace std。 class CTest{ public: const int y2。 CTest (int i1,int i2):y1(i1),y2(i2) { y1=10。 x=y1。 } int readme() const。 //... private: int x。 const int y1。 }。 int CTest::readme() const { int i。 i=x。 x++。 return x。 } int main() { CTest c(2,8)。 int i=c.y2。 c.y2=i。 i=c.y1。 return 0。 } 【解】 #include using namespace std。 class CTest{ public: const int y2。 CTest (int i1,int i2):y1(i1),y2(i2) { y1=10。 // 错误,y1是用const定义的,不能修改 x=y1。 } int readme() const。 //... private: int x。 15 / 72 const int y1。 }。 int CTest::readme() const { int i。 i=x。 x++。 // 错误,函数定义用了const,表示该函数不能修改对象 return x。 } int main() { CTest c(2,8)。 int i=c.y2。 c.y2=i。 // 错误,y2是常量,不能修改 i=c.y1。 // 错误,y1私有变量,不能直接存取 return 0。 } 【4.18】指出下面程序中的错误,并说明原因。 #include using namespace std。 class CTest{ public: CTest () { x=20。 } void use_friend()。 private: int x。 friend void friend_f(CTest fri)。 }。 void friend_f(CTest fri) { fri.x=55。 } void CTest::use_friend() { CTest fri。 this->friend_f(fri)。 ::friend_f(fri)。 } int main() { CTest fri,fri1。 fri.friend_f(fri)。 friend_f(fri1)。 return 0。 } 【解】 #include 16 / 72 using namespace std。 class CTest{ public: CTest() { x=20。 } void use_friend()。 private: int x。 friend void friend_f(CTest fri)。 }。 void friend_f(CTest fri) { fri.x=55。 } void CTest::use_friend() { CTest fri。 this->friend_f(fri)。 // 错误, 友元函数不是成员函数, // 所以不能用this->调用友元函数 ::friend_f(fri)。 } int main() { CTest fri,fri1。 fri.friend_f(fri)。 // 错误友元函数不是成员函数, // 所以不能用“对象.函数名”调用友元函数 friend_f(fri1)。 return 0。 } 【4.19】指出下面程序中的错误,并说明原因。 #include using namespace std。 class CTest{ public: CTest () { x=20。 } void use_this()。 private: int x。 }。 void CTest::use_this() { CTest y,*pointer。 this=&y。 *this.x=10。 pointer=this。 17 / 72 pointer=&y。 } int main() { CTest y。 this->x=235。 return 0。 } 【解】 #include using namespace std。 class CTest{ public: CTest () { x=20。 } void use_this()。 private: int x。 }。 void CTest::use_this() { CTest y,*pointer。 this=&y。 // 错误,不能对this直接赋值。 *this.x=10。 // 错误, 按优先级原句的含义是*(this.x)=10,显然不对 // 正确的写法是(*this).x=10。或 this->x=10。 pointer=this。 pointer=&y。 } int main() { CTest y。 this->x=235。 // 错误,this的引用不能在外部函数中,只能在内部函数中。 Return 0。 } 【4.20】写出下面程序的运行结果。 #include using namespace std。 class toy {public: toy(int q, int p) {quan = q。 price = p。 } int get_quan() { return quan。 } 18 / 72 int get_price() { return price。 } private: int quan, price。 }。 int main() { toy op[3][2]={ toy(10,20),toy(30,48), toy(50,68),toy(70,80), toy(90,16),toy(11,120), }。 for (int i=0。i<3。i++) { cout<。 cout<。 cout<。 cout<。 } cout<。 return 0。 } 【4.21】写出下面程序的运行结果。 #include using namespace std。 class example {public: example(int n) { i=n。 cout<<"Constructing\n "。 } ~example() { cout <<"Destructing\n"。 } int get_i() { return i。 } private: int i。 }。 int sqr_it(example o) { return o.get_i()* o.get_i()。 } int main() { example x(10)。 19 / 72 cout<。 cout<。 return 0。 } 【4.22】写出下面程序的运行结果。 #include using namespace std。 class aClass {public: aClass() { total++。} ~aClass() { total--。} int gettotal() { return total。} private: static int total。 }。 int aClass::total=0。 int main() { aClass o1,o2,o3。 cout<。 aClass *p。 p=new aClass。 if (!p) { cout<<"Allocation error\n"。 return 1。 } cout<。 cout<<" objects in existence after allocation\n"。 delete p。 cout<。 cout<<" objects in existence after deletion\n"。 return 0。 } 【4.23】写出下面程序的运行结果。 #include using namespace std。 class test {public: test() 。 ~test(){ }。 private: 20 / 72 int i。 }。 test::test() { i = 25。 cout<<"Here's the program output. \n"。 cout<<"Let′s generate some stuff...\n"。 for (int ctr=0。 ctr<10。 ctr++) { cout<<"Counting at "<。 } } test anObject。 int main( ) { return 0。 } 【4.24】 构建一个类book,其中含有两个私有数据成员qu和price, 建立一个有5个元素的数组对象,将qu初始化为1~5,将price 初始化为qu的10倍。显示每个对象的qu*price。 【解】实现本题功能的程序如下: #include using namespace std。 class book {public: book(int a, int b) {qu= a。 price= b。 } void show_money() { cout<。} private: int qu,price。 }。 int main() { book ob[5]={ book(1,10),book(2,20), book(3,30),book(4,40),book(5,50) }。 int i。 for(i=0。 i<5。 i++) ob[i].show_money()。 return 0。 } 【4.25】 修改上题,通过对象指针访问对象数组,使程序以相反的顺序显示对象数组的qu*price。 【解】实现本题功能的程序如下: #include 21 / 72 using namespace std。 class book {public: book(int a, int b) { qu= a。 price= b。 } void show_money() { cout<。} private: int qu,price。 }。 int main() { book ob[5]={ book(1,10),book(2,20), book(3,30),book(4,40), book(5,50) }。 int i。 book *p。 p=&ob[4]。 for(i=0。 i<5。 i++) { p->show_money()。p--。} return 0。 } 【4.26】使用 C++ 的类建立一个简单的卖玩具的程序。类内必须具有玩具单价、售出数量以及每种玩具售出的总金额等数据,并为该类建立一些必要的函数,并在主程序中使用对象数组建立若干个带有单价和售出数量的对象,显示每种玩具售出的总金额。 【解】实现本题功能的程序如下: #include using namespace std。 class toy {public: toy(){ } toy(int p,int c) { Price=p。 Count=c。 } void Input(int P, int C) 。 void Compute() 。 void Print() 。 private: int Price。 int Count。 22 / 72 long Total。 }。 void toy::Input (int P, int C) { Price=P。 Count=C。 } void toy::Compute() { Total=(long) Price*Count。 } void toy::Print() { cout<<"Price="<。 } int main() { toy te(2,100)。// 测试构造函数 toy* ob。 ob = new toy[6]。 ob[0].Input(25,130)。 ob[1].Input(30,35)。 ob[2].Input(15,20)。 ob[3].Input(25,120)。 ob[4].Input(45,10)。 ob[5].Input(85,65)。 for (int i=0。 i<6。 i++) ob[i].Compute()。 for (i=0。 i<6。 i++) ob[i].Print()。 delete ob。 return 0。 } 【4.27】 构建一个类Stock,含字符数组stockcode[]及整型数据成员quan、双精度型数据成员price。构造函数含3个参数:字符数组na[]及q、p。当定义Stock的类对象时,将对象的第1个字符串参数赋给数据成员stockcode,第2和第3个参数分别赋给quan、price。未设置第2和第3个参数时,quan的值为1000,price的值为8.98。成员函数 print()使用this指针,显示对象内容。 【解】实现本题功能的程序如下: #include using namespace std。 const int SIZE=80。 class Stock{ public: Stock() {strcpy(stockcode," ")。 } 23 / 72 Stock(char code[], int q=1000, double p=8.98) { strcpy(stockcode, code)。 quan=q。 price= p。 } void print(void) { cout<stockcode。 cout<<" "<quan<<" "<price<。 } private: char stockcode[SIZE]。 int quan。 double price。 }。 int main() { Stock st1("600001", 3000, 8.89)。 st1.print()。 Stock st2。 char stockc[]="600002"。 st2=stockc。 st2.print()。 return 0。 } 【4.28】 编写一个有关股票的程序,其中有两个类:一个是深圳类shen_stock,另一个是上海类shang_stock。类中有三项私有数据成员:普通股票个数general、ST股票个数st和PT股票个数pt,每一个类分别有自己的友元函数来计算并显示深圳或上海的股票总数(三项的和)。两个类还共用一个count(),用来计算深圳和上海总共有多少股票并输出。 【解】实现本题功能的程序如下: #include using namespace std。 class shen_stock。 // 向前引用 class shang_stock // 深圳类 {public: shang_stock(int g,int s,int p)。 // 构造函数 friend void shang_count(const shang_stock ss)。 // 计算上海的股票总数 friend void count(const shang_stock ss,const shen_stock zs)。 // 计算上海和深圳的股票总数 private: int general。 // 普通股票个数 int st。 // ST股票个数 int pt。 // PT股票个数 }。 24 / 72 shang_stock:: shang_stock(int g,int s,int p) // 构造函数 { general=g。 st=s。 pt=p。 } class shen_stock{ int general。 // 普通股票个数 int st。 // ST股票个数 int pt。 // PT股票个数 public: shen_stock(int g,int s,int p )。 // 构造函数 friend void shen_count(const shen_stock es)。 // 计算深圳的股票总数 friend void count(const shang_stock ss,const shen_stock zs)。 // 计算上海和深圳的股票总数 }。 shen_stock::shen_stock(int g,int s,int p) // 构造函数 {general=g。 st=s。 pt=p。 } int main() {shang_stock shanghai(1600,20,10)。 // 建立对象 // 表示上海有1600支普通股票,20支ST股票, 10支PT股票 shen_stock shenzhen(1500,15,8)。 // 建立对象 // 表示深圳有1500支普通股票,15支ST股票,8支PT股票 shang_count(shanghai)。 // 计算上海的股票总数 shen_count(shenzhen)。 // 计算深圳的股票总数 count(shanghai,shenzhen)。 // 计算上海和深圳的股票总数 return 0。 } void shang_count(const shang_stock ss) // 计算上海的股票总数 { cout<<"stocks of shanghai are "<。 } void shen_count(const shen_stock es) // 计算深圳的股票总数 { cout<<"stocks of shanghai are "<。 } void count(const shang_stock ss,const shen_stock es) { // 计算上海和深圳的股票总数 int s。 s= es.general+es.st+es.pt+ ss.general+ss.st+ss.pt。 cout<<"stocks of shanghai and shenzhen "<。 } 【4.29】编写一个程序,已有若干学生的数据,包括学号、姓名、成绩,要求输出这些学生的数据并计算出学生人数和平均成绩(要求将学生人数和总成绩用静态数据成员表示)。 25 / 72 【解】实现本题功能的程序如下: #include using namespace std。 class Student{ public: Student(int n,string na,double d) { no=n。 deg=d。 name=na。 sum+=d。 num++。 } static double avg() { return sum/num。 } static int total() { return num。 } void disp() { cout<。 } private: int no。 //学号 string name。 //姓名 double deg。 //成绩 static double sum。 //总成绩 static int num。 //学生人数 }。 double Student::sum=0。 int Student::num=0。 int main() { Student s1(1001,"Zhou",97),s2(1002,"Zhan",65),s3(1003,"Chen",88)。 cout<<"学号 姓名 成绩\n"。 s1.disp()。 s2.disp()。 s3.disp()。 cout<<"学生人数="<。 cout<<"平均成绩="<。 return 0。 } 第5章继承与派生 26 / 72 【5.13】写出下面程序的运行结果。 #include using namespace std。 class B1{ public: B1(int i) { b1=i。 cout<<"Constructor B1. "<。 } void Print() { cout<。 } private: int b1。 }。 class B2{ public: B2(int i) { b2=i。 cout<<"Constructor B2. "<。 } void Print() { cout<。 } private: int b2。 }。 class A:public B2,public B1{ public: A(int i,int j,int l)。 void Print()。 private: int a。 }。 A::A(int i,int j,int l):B1(i),B2(j) { a=l。 cout<<"Constructor A. "<。 } void A::Print() { B1::Print()。 B2::Print()。 cout<。 } int main() { A aa(3,2,1)。 27 / 72 aa.Print()。 return 0。 } 【5.14】写出下面程序的运行结果。 #include using namespace std。 class Main{ protected: char *mainfood。 public: Main(char *name) { mainfood=name。 } }。 class Sub{ protected: char *subfood。 public: Sub(char *name) { subfood=name。 } }。 class Menu:public Main,public Sub{ public: Menu(char *m, char *s):Main(m),Sub(s) { } void show()。 }。 void Menu::show() { cout<<"主食="<。 cout<<"副食="<。 } int main() {Menu m("bread","steak")。 m.show()。 return 0。 } 【5.15】写出下面程序的运行结果。 #include using namespace std。 class A{ private: int a。 public: 28 / 72 A() {a=0。} A(int i) { a=i。} void Print() { cout<。 } }。 class B:public A{ private: int b1,b2。 public: B() { b1=0。 b2=0。 } B(int i) { b1=i。 b2=0。 } B(int i,int j,int k):A(i),b1(j),b2(k) {} void Print() { A::Print()。 cout<。 } }。 int main() { B ob1,ob2(1),ob3(3,6,9)。 ob1.Print()。 ob2.Print()。 ob3.Print()。 return 0。 } 【5.16】写出下面程序的运行结果。 #include using namespace std。 class B1{ int b1。 public: B1(int i) { b1=i。 cout<<"constructor B1."<。 } void print() { cout<。 29 / 72 } }。 class B2{ int b2。 public: B2(int i) { b2=i。 cout<<"constructor B2."<。 } void print() { cout<。 } }。 class B3{ int b3。 public: B3(int i) { b3=i。 cout<<"constructor B3."<。 } int getb3() { return b3。 } }。 class A :public B2,public B1{ int a。 B3 bb。 public: A(int i,int j,int k,int l):B1(i),B2(j),bb(k) { a=l。 cout<<"constructor A."<。 } void print() { B1::print()。 B2::print()。 cout<。 } }。 int main() { A aa(1,2,3,4)。 aa.print()。 return 0。 } 【5.17】下面的程序可以输出ASCII字符与所对应的数字的对照表。修改下列程序,使其可以输出字母a 到z与所对应的数字的对照表。 30 / 72 #include using namespace std。 #include class table{ public: table(int p) { i=p。 } void ascii(void)。 protected : int i。 }。 void table::ascii(void) { int k=1。 for (。i<127。i++) { cout<。 if ((k)%12==0) cout<<"\n"。 k++。 } cout<<"\n"。 } class der_table:public table { public: der_table(int p,char *m):table(p) {c=m。} void print(void)。 protected: char *c。 }。 void der_table::print(void) { cout<。 table::ascii()。 } int main() { der_table ob1(32,"ASCII value---char")。 ob1.print()。 return 0。 } 提示:修改后的主程序为: int main() { der_table ob('a','z',"ASCII value---char")。 ob.print()。 return 0。 } 31 / 72 【解】 修改后的程序如下: #include using namespace std。 #include class table{ protected : int i。 int j。 public: table(int p,int q) { i=p。 j=q。 } void ascii(void)。 }。 void table::ascii(void) { int k=1。 for (。i<=j。i++) { cout<。 //“setw(4)”表示数字域宽为4 if ((k)%12==0) cout<<"\n"。 k++。 } cout<<"\n"。 } class der_table:public table{ protected: char *c。 public: der_table(int p,int q,char *m):table(p,q) { c=m。 } void print(void)。 }。 void der_table::print( ) { cout<。 table::ascii()。 } int main() { der_table ob('a','z',"ASCII value---char")。 ob.print()。 return 0。 } 【5.18】给出下面的基类: 32 / 72 class area_cl { protected: double height。 double width。 public: area_cl(double r,double s) { height=r。width=s。} virtual double area()=0。 }。 要求: (1)建立基类area_cl的两个派生类rectangle与isosceles,让每一个派生类都包含一个函数area(),分别用来返回矩形与三角形的面积。用构造函数对height与width进行初始化。 (2)写出主程序,用来求height与width分别为10.0与5.0的矩形面积,以及求height与width分别为4.0与6.0的三角形面积 (3)要求通过使用基类指针访问虚函数的方法(即运行时的多态性)分别求出矩形和三角形面积。 【解】实现本题功能的程序如下: #include using namespace std。 class area_cl{ protected: double height。 double width。 public: area_cl(double r,double s) {height=r。 width=s。 } virtual double area()=0。 }。 class rectangle:public area_cl{ public: rectangle(double r,double s):area_cl(r,s) { }。 double area() {return height*width。 } }。 class isosceles:public area_cl{ public: isosceles(double r,double s):area_cl(r,s) {}。 double area(){return height*width/2。} 33 / 72 }。 int main() { area_cl *p。 rectangle b(10.0,5.0)。 isosceles i(4.0,6.0)。 p=&b。 cout<<"The rectangle's area is "<area()<。 p=&i。 cout<<"The isoceles's area is "<area()<。 return 0。 } 【5.19】已有类Time和Date,要求设计一个派生类Birthtime,它继承类Time和Date,并且增加一个数据成员Childname用于表示小孩的名字,同时设计主程序显示一个小孩的出生时间和名字。 class Time{ public: Time(int h,int m,int s) { hours=h。 minutes=m。 seconds=s。 } void display() { cout<<"出生时间:"<时"<分"<秒"<。 } protected: int hours,minutes,seconds。 }。 class Date{ public: Date(int m,int d,int y) { month=m。 day=d。 year=y。 } void display() { cout<<"出生年月:"<年"<月"<日"<。 } protected: int month,day,year。 }。 【解】 修改后的程序如下: #include using namespace std。 class Time{ 34 / 72 public: Time(int h,int m,int s) { hours=h。 minutes=m。 seconds=s。 } void display() { cout<<"出生时间:"<时"<分"<秒"<。 } protected: int hours,minutes,seconds。 }。 class Date{ public: Date(int m,int d,int y) { month=m。 day=d。 year=y。 } void display() { cout<<"出生年月:"<年"<月"<日"<。 } protected: int month,day,year。 }。 class Birthtime:public Time,public Date { public: Birthtime(char *Cn,int yy,int mm,int dd,int hh,int mint,int ss) :Time (hh,mint,ss),Date(mm,dd,yy) { strcpy(Childname,Cn)。 } void display() { cout<<"姓 名:"<。 Date::display()。 Time::display()。 } protected: char Childname[20]。 }。 int main() { Birthtime yx("王小明" ,2001,12,17,18,20,30)。 yx.display()。 return 0。 } 【5.20】编写一个学生和教师数据输入和显示程序,学生数据有编号、姓名、班号和成35 / 72 绩,教师数据有编号、姓名、职称和部门。要求将编号、姓名输入和显示设计成一个类person,并作为学生数据操作类student和教师数据操作类teacher的基类。 【解】实现本题功能的程序如下: #include using namespace std。 class person{ public: void input() { cout<<" 编号:"。 cin>>no。 cout<<" 姓名: "。 cin>>name。 } void disp() { cout<<" 编号:"<。 cout<<" 姓名: "<。 } private: int no。 char name[10]。 }。 class student:public person{ public: void input() { person::input()。 cout<<" 班号:"。 cin>>depart。 cout<<" 成绩:"。 cin>>degree。 } void disp() { person::disp()。 cout<<" 班号:"<。 cout<<" 成绩:"<。 } private: char depart[6]。 int degree。 }。 class teacher:public person{ private: char prof[10]。 char depart[10]。 public: void input() { person::input()。 36 / 72 cout<<" 职称:"。 cin>>prof。 cout<<" 部门:"。 cin>>depart。 } void disp() { person::disp()。 cout<<" 职称:"<。 cout<<" 部门:"<。 } }。 int main() { student s1。 teacher t1。 cout<<" 输入一个学生数据:\n"。 s1.input()。 cout<<" 输入一个教师数据:\n"。 t1.input()。 cout<<" 显示一个学生数据:\n"。 s1.disp()。 cout<<" 显示一个教师数据:\n"。 t1.disp()。 return 0。 } 【5.21】编一个程序,递归调用被继承的基类成员函数,实现求素数的功能。 【解】实现本题功能的程序如下: #include using namespace std。 class prime{ private: int x。 public: prime (int p)。 int pri_function(int j)。 }。 prime::prime(int p) { x=p。 }。 int prime::pri_function(int j) { for (int t=2,flag=1 。t。t++) if (j%t==0) flag=0。 return flag。 } class derived:public prime{ 37 / 72 protected: char *c。 public: derived (char *m)。 int pf(int l)。 }。 derived::derived(char *m):prime(2) { c=m。 } int derived::pf(int l) { return prime::pri_function(l)。 } int main() { derived ob("prime\n")。 int n。 cout<<"please input a int:"。 cin>>n。 if (ob.pf(n)==1) cout<。 else cout<。 return 0。 } 【5.22】编一个程序,递归调用被继承的基类成员函数,求最大公约数。 【解】 实现本题功能的程序如下: #include using namespace std。 class gcd_class{ private: int n。 int d。 public: gcd_class (int p,int q)。 long func(int j,int k)。 }。 gcd_class::gcd_class(int p,int q) { n=p。 d=q。 } long gcd_class::func(int j,int k) { if (k==0) return j。 else return func(k,j%k)。 } 38 / 72 class derived:public gcd_class{ protected: char *c。 public: derived (char *m)。 long pfunc(int l,int r)。 }。 derived::derived(char *m):gcd_class(1,1) { c=m。 } long derived::pfunc(int l,int r) { return gcd_class::func(l,r)。 }。 int main() { derived ob(" output n!\n")。 int n,d。 cout<<"please input two int:"。 cin>>n>>d。 cout<<"gcd("<。 return 0。 } 第6章多态性与虚函数 【6.9】有如下程序: #include using namespace std。 class shapes {protected: int x,y。 public: void setvalue(int d,int w=0) { x=d。 y=w。 } virtual void disp()=0。 }。 class square:public shapes{ public: void disp() {cout<。 } 39 / 72 }。 int main() {shapes *ptr。 square s1。 ptr=&s1。 ptr->setvalue(10,5)。 ptr->disp()。 return 0。 } 执行上面的程序将输出( )。 A)50 B)5 C)10 D) 15 【6.11】分析以下程序的运行结果: #include using namespace std。 class Stock{ public: void print() { cout<<"Stock class.\n"。 } }。 class Der1_Stock:public Stock{ public: void print() { cout<<"Der1_Stock class.\n"。 } }。 class Der2_Stock: public Stock{ public: void print() { cout<<"Der2_Stock class.\n"。 } }。 int main() { Stock s1。 Stock *ptr。 Der1_Stock d1。 Der2_Stock d2。 ptr=&s1。 ptr->print()。 ptr=&d1。 ptr->print()。 ptr=&d2。 ptr->print()。 40 / 72 return 0。 } 【6.12】修改上一题的程序,使运行结果为: Stock class. Der1_Stock class. Der2_Stock class. 【解】 修改后的程序如下: #include using namespace std。 class Stock{ public: virtual void print() // 修改的地方 {cout<<"Stock class.\n"。 } }。 class Der1_Stock: public Stock{ public: void print() {cout<<"Der1_Stock class.\n"。 } }。 class Der2_Stock: public Stock{ public: void print() {cout<<"Der2_Stock class.\n"。 } }。 int main() {Stock s1。 Stock *ptr。 Der1_Stock d1。 Der2_Stock d2。 ptr=&s1。 ptr->print()。 ptr=&d1。 ptr->print()。 ptr=&d2。 ptr->print()。 return 0。 } 【6.13】 定义基类Base,其数据成员为高h,定义成员函数disp为虚函数。然后再由High派生出长方体类Cuboid与圆柱体类Cylinder。并在两个派生类中定义成员函数disp为虚函数。在主函数中,用基类Base定义指针变量pc,然后用指针pc动态调用基类与派生类中虚函数disp,显示长方体与圆柱体的体积。 41 / 72 【解】实现本题功能的程序如下: #include using namespace std。 class Base{ public: Base() { } Base(double h1) { h=h1。} virtual void disp() //虚函数disp { cout<<"长方体和圆柱体的高度都是:"<。 } protected: double h。 //高度 }。 class Cuboid:public Base{ //长方体类 public: Cuboid(double l=0,double w=0,double h=0):Base(h) { len=l, wid=w。 } void disp() //虚函数disp { cout<<"长方体:"<。 cout<<" 长度="<。 cout<<" 宽度="<。 cout<<" 高度="<。 cout<<" 长方体的体积="<。 } private: double len,wid。 //长度和宽度 }。 class Cylinder:public Base { //圆柱体类 public: Cylinder(double r1=0,double h1=0):Base(h1) { r=r1。} void disp() //虚函数disp { cout<<"圆柱体:"<。 cout<<" 半径="<。 cout<<" 高度="<。 cout<<" 圆柱体的体积="<。 } private: double r。 //半径 }。 42 / 72 int main() { Base *pc。 Cuboid cu(5,6,8)。 Cylinder cy(5,6)。 pc=&cu。 pc->disp()。 pc=&cy。 pc->disp()。 return 0。 } 【6.14】给出下面的抽象基类container: class container{ //声明抽象类container protected: double radius。 public: container(double radius1)。 //抽象类container的构造函数 virtual double surface_area()=0。 //纯虚函数surface_area virtual double volume()=0。 //纯虚函数volume }。 要求建立三个继承container 的派生类cube、sphere与cylinder,让每一个派生类都包含虚函数surface_area()和volume(),分别用来计算正方体、球体和圆柱体的表面积及体积。要求写出主程序,应用C++的多态性,分别计算边长为6.0的正方体、半径为5.0的球体,以及半径为5.0和高为6.0的圆柱体的表面积和体积。 【解】实现本题功能的程序如下: #include using namespace std。 class container{ //声明抽象类container protected: double radius。 public: container(double radius1)。 //抽象类container的构造函数 virtual double surface_area()=0。 //纯虚函数surface_area virtual double volume()=0。 //纯虚函数volume }。 container::container(double radius1) //定义抽象类container的构造函数 { radius=radius1。 } class cube:public container //声明一个正方体派生类cube { public: cube(double radius1):container(radius1) { } double surface_area() //定义虚函数surface_area { return 6*radius*radius。 } 43 / 72 double volume() //定义虚函数volume { return radius*radius*radius。 } }。 class sphere:public container //声明一个球体派生类sphere { public: sphere(double radius1):container(radius1) { }。 double surface_area() //纯虚函数surface_area { return 4*3.1416*radius*radius。 } double volume() //纯虚函数volume { return 3.1416*radius*radius*radius*4/3。 } }。 class cylinder:public container //声明一个圆柱体派生类cylinder { double height。 public: cylinder(double radius1,double height1):container(radius1) { height=height1。 } double surface_area() //定义虚函数surface_area { return 2*3.1416*radius*(radius+height)。 } double volume() //定义虚函数volume { return 3.1416*radius*radius*height。 } }。 int main() { container *ptr。 //定义抽象类Shape的对象指针ptr cube obj1(5.0)。 //定义正方体的类对象obj1 sphere obj2(5.0)。 //定义球体的类对象obj2 cylinder obj3(5.0,6.0)。 //定义圆柱体的类对象obj2 ptr=&obj1。 //指针ptr指向正方体类对象obj1 cout<<"这个正方体的表面积是:"<surface_area()<。 //求正方体的表面积 cout<<"这个正方体的体积是:"<volume()<。 //求正方体的的体积 ptr=&obj2。 //指针ptr指向球体的类对象obj2 cout<<"这个球体表面积是:"<surface_area()<