C 面向对象程序设计习题解答与上机指导(第二版)源程序

2022-08-05 11:21:53   文档大全网     [ 字体:小 中 大 ] [ 阅读: ]

【#文档大全网# 导语】以下是®文档大全网的小编为您整理的《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()<。 //求球体的表面积 cout<<"这个球体的体积是:"<volume()<。 //求球体的的体积 ptr=&obj3。 //指针ptr指向圆柱体类的对象obj3 cout<<"这个圆柱体的表面积是:"<surface_area()<。

44 / 72


//求圆柱体的表面积

cout<<"这个圆柱体的体积是:"<volume()<。 //求圆柱体的的体积 return 0。 }

第7章 运算符重载



【7.6】写出下列程序的运行结果。 #include using namespace std。 class A { public:

A(int i):x(i) { } A()

{ x=0。 }

friend A operator ++(A a)。 friend A operator --(A &a)。 void print()。 private: int x。 }。

A operator++(A a) { ++a.x。 return a。 }

A operator --(A &a) { --a.x。 return a。 }

void A::print() { cout<。 }

int main() { A a(7)。 ++a。

a.print()。 --a。

a.print()。 return 0。

45 / 72


}

【7.7】写出下列程序的运行结果。 #include using namespace std。 class Words{ public:

Words(char *s)

{ str=new char[strlen(s)+1]。 strcpy(str,s)。 len=strlen(s)。 }

void disp()。

char operator[](int n)。 //定义下标运算符“[]”重载函数 private: int len。 char*str。 }。

char Words::operator[](int n)

{ if (n<0||n>len-1) //数组的边界检查 { cout<<"数组下标超界!\n"。 return ' '。 } else

return *(str+n)。 }

void Words::disp() { cout<。 }

int main()

{ Words word("This is C++ book.")。 word.disp()。

cout<<"第1个字符:"。

cout<。//word[0]被解释为word.operator[](0) cout<<"第16个字符:"。 cout<。 cout<<"第26个字符:"。 cout<。 return 0。 }

【7.8】写出下列程序的运行结果。 #include using namespace std。 class Length { int meter。

46 / 72


public:

Length(int m) { meter=m。 }

operator double()

{ return (1.0*meter/1000)。 } }。

int main()

{ Length a(1500)。 double m=float(a)。

cout<<"m="<千M"<。 return 0。 }

【7.9】写出下列程序的运行结果。 #include using namespace std。 class Array{ public:

Array(int)。

int& operator()(int)。 //重载运算符() private: int *m。 int x。 }。

Array::Array(int x) { this->x=x。 m=new int[x]。

for(int i=0。i。i++) *(m+i)=i。 }

int& Array::operator()(int x1) { return(*(m + x1))。 }

int main( )

{ cout<<"\n\n"。 Array a(10)。 cout<。 a(5)=7。

cout<。 return 0。 }

【7.10】编一个程序,用成员函数重载运算符“+”和“-”将两个二维数组相加和相减,要求第1个二维数组的值由构造函数设置,另一个二维数组的值由键盘输入。

47 / 72


【解】 实现本题功能的程序如下: #include #include using namespace std。 const int row=2。 const int col=3。 class array { public:

array()。 //构造函数 array(int a,int b,int c,int d,int e,int f)。

void get_array( )。 //由键盘输入数组的值 void display()。 //显示数组的值

array operator+(array &X)。 //将两个数组相加

array operator-(array &X)。 //将两个数组相减 private:

int var[row][col]。 }。

array::array()

{ for(int i=0。 i。 i++) for(int j=0。j。 j++) var[i][j]=0。

}

array::array(int a,int b,int c,int d,int e,int f) { //由构造函数设置数组的值 var[0][0]=a。

var[0][1]=b。 var[0][2]=c。 var[1][0]=d。

var[1][1]=e。 var[1][2]=f。 }

void array::get_array( ) //由键盘输入数组的值 { cout<<"Please input 2*3 dimension data:"<。 for (int i=0。 i。 i++) for (int j=0。j。 j++) cin>>var[i][j]。

}

void array::display() //显示数组的值 { for (int i=0。 i。i++) { for (int j=0。j。j++ ) cout<。 cout<。

}

}

48 / 72


array array::operator+(array &X) //将两个数组相加 { array temp。

for (int i=0。i。 i++) for(int j=0。j。j++)

temp.var[i][j]=var[i][j]+X.var[i][j]。 return temp。 }

array array::operator-(array &X) //将两个数组相减 { array temp。 for (int i=0。 i。 i++) for (int j=0。 j。 j++ ) temp.var[i][j]=var[i][j]-X.var[i][j]。 return temp 。 }

int main()

{ array X(11,22,33,44,55,66)。 array Y,Z。 Y.get_array()。

cout<<"Display object X"<。

X.display()。

cout<<"Display object Y"<。

Y.display()。 Z=X+Y。

cout<<" Display object Z=X+Y"<。 Z.display()。 Z=X-Y。

cout<<" Display object Z=X-Y"<。

Z.display()。 return 0。

}

【7.11】修改上题,用友元函数重载运算符“+”和“-”将两个二维数组相加和相减。 【解】实现本题功能的程序如下: #include #include using namespace std。

const int row=2。 const int col=3。 class array { public:

array()。 //构造函数 array(int a,int b,int c,int d,int e,int f)。

void get_array( )。 //由键盘输入数组的值

void display()。 //显示数组的值

friend array operator+(array &X,array &Y)。 //将两个数组相加 friend array operator-(array &X,array &Y)。 //将两个数组相减

49 / 72


private:

int var[row][col]。 }。

array::array()

{ for (int i=0。 i。 i++) for (int j=0。j。 j++) var[i][j]=0。

}

array::array(int a,int b,int c,int d,int e,int f)

{ // 由构造函数设置数组的值 var[0][0]=a。 var[0][1]=b。 var[0][2]=c。 var[1][0]=d。 var[1][1]=e。 var[1][2]=f。 }

void array::get_array( ) //由键盘输入数组的值 { cout<<" Please input 2*3 dimension data: "<。 for (int i=0。 i。 i++) for (int j=0。j。 j++) cin>>var[i][j]。

}

void array::display() //显示数组的值 { for (int i=0。 i。i++) { for (int j=0。j。j++ ) cout<。 cout<。

}

}

array operator+(array &X,array &Y) //将两个数组相加 { array temp。

for (int i=0。i。 i++) for (int j=0。j。j++)

temp.var[i][j]=Y.var[i][j]+X.var[i][j]。 return temp。

}

array operator-(array &X,array &Y) //将两个数组相减 { array temp。

for (int i=0。 i。 i++) for (int j=0。 j。 j++ )

temp.var[i][j]=X.var[i][j]-Y.var[i][j]。 return temp 。 }

int main()

{ array X(11,22,33,44,55,66)。 array Y,Z。 Y.get_array()。

cout<<"Display object X"<。 X.display()。

50 / 72


cout<<"Display object Y"<。 Y.display()。 Z=X+Y。

cout<<" Display object Z=X+Y"<。 Z.display()。 Z=X-Y。

cout<<" Display object Z=X-Y"<。 Z.display()。 return 0。

}

【7.12】编写一个程序,要求:

1.声明一个类complex,定义类complex的两个对象cl和c2, 对象cl通过构造函数直接指定复数的实部和虚部(类私有数据成员为double类型的real和imag)为2.5及3.7,对象c2通过构造函数直接指定复数的实部和虚部为4.2及6.5;

2. 定义友元运算符重载函数,它以 cl、c2对象为参数,调用该函数时能返回两个复数对象相加操作;

3.定义成员函数print,调用该函数时,以格式“(real,imag)”输出当前对象的实部和虚部,例如:对象的实部和虚部分别是4.2和6.5,则调用print函数输出格式为:(4.2,6.5);

4.编写主程序,计算出复数对象c1和c2相加结果,并将其结果输出。 【解】实现本题功能的程序如下: #include using namespace std。 class complex{ public:

complex(double r=0,double i=0)。

friend complex operator+(const complex c1,const complex c2)。 void print() 。

private:

double real,imag。

}。

complex::complex(double r,double i) { real=r。 imag=i。

}

complex operator+(const complex c1,const complex c2) { complex temp。 temp.real=c1.real+c2.real。 temp.imag=c1.imag+c2.imag。 return temp。

}

void complex::print()

{ cout<<" ("<。 }

int main()

{ complex c1(2.5,3.7),c2(4.2,6.5)。 complex c。

51 / 72


c=c1+c2。 c.print()。 return 0。

}

【7.13】为Date类重载“+” 运算符,实现在某一个日期上(月、日、年)加一个天数。Date类如下:

class Date{ public: Date(){ } Date(int m,int d,int y) { month=m。

day=d。 year=y。 }

void print() { cout<。 } Date operator +(int)。 private: int month,day,year。

}。

【解】实现本题功能的程序如下: #include using namespace std。 class Date{ public: Date(){ } Date(int m,int d,int y) { month=m。

day=d。 year=y。 }

void print() { cout<。 } Date operator +(int)。 private: int month,day,year。

}。

static int days[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31}, {31,29,31,30,31,30,31,31,30,31,30,31}}。

int isleap(int year)

{if ((year%4==0&&year%100!=0)||(year%400==0))

return 1。

52 / 72


else

return 0。

}

Date Date::operator+(int n) { int leap。 leap=0。

leap=isleap(this->year)。 n+=this->day。

while (n>days[leap][this->month-1]) { n-=days[leap][this->month-1]。 if (++(this->month)==13)

{ this->month=1。(this->year)++。

leap=isleap(this->year)。 } }

this->day=n。 return *this。

}

int main()

{ Date d1(2,15,2000),d2。 d1.print()。 d2=d1+365。 d2.print()。 return 0。

}

【7.14】 定义一个矩阵类Matrix,重载运算符"+",使之能用于矩阵的加法运算。有两个矩阵a和b,均为2行4列。求两个矩阵之和。重载流插入运算符"<<"和流提取运算符">>",使之能用于该矩阵的输入和输出。

【解】实现本题功能的程序如下: #include using namespace std。 class Matrix{ public: Matrix()。

friend Matrix operator+(Matrix&,Matrix&)。 //声明重载运算符"+" friend ostream& operator<<(ostream&,Matrix&)。 //声明重载运算符"<<" friend istream& operator>>(istream&,Matrix&)。//声明重载运算符">>"

private: int mat[2][4]。

}。

Matrix::Matrix()

{for(int i=0。i<2。i++) for(int j=0。j<4。j++) mat[i][j]=0。

53 / 72


}

Matrix operator+(Matrix& a,Matrix& b) //定义运算符"+"的重载函数 {Matrix c。

for(int i=0。i<2。i++) for(int j=0。j<4。j++)

{c.mat[i][j]=a.mat[i][j]+b.mat[i][j]。}

return c。 }

istream& operator>>(istream& in,Matrix& m) //定义运算符">>"的重载函数 {cout<<"input value of matrix:"<。 for(int i=0。i<2。i++) for(int j=0。j<4。j++)

in>>m.mat[i][j]。

return in。 }

ostream& operator<<(ostream& out,Matrix& m) //定义运算符"<<"的重载函数 {for(int i=0。i<2。i++) {for(int j=0。j<4。j++) {out<。}

out<。 }

return out。 }

int main()

{ Matrix a,b,c。

cin>>a。 //用cin输入矩阵a cin>>b。//用cin输入矩阵b

cout<<"Matrix a:"<。 //用cout输出矩阵a cout<<"Matrix b:"<。//用cout输出矩阵b c=a+b。

cout<<"Matrix c=Matrix a + Matrix b:"<。//用cout输出矩阵c return 0。 }

第8章函数模板与类模板



【8.12】写出下面程序的运行结果。 #include using namespace std。

template class myclass{ public:

myclass(Type1 a,Type2 b)

54 / 72


{ i=a。 j=b。 }

void show()

{ cout<′′<′\n′。 }

private: Type1 i。 Type2 j。 }。

int main()

{ myclass ob1(10,0.23)。

myclass ob2(′X′,"This is a test.")。 ob1.show()。 ob2.show()。 return 0。 }

【8.13】写出下面程序的运行结果。 #include using namespace std。 template T min(T a,T b) {

if(a。 else return b。 }

int main()

{ int n1=5,n2=81。

double d1=1.3,d2=5.6。

cout<<"较小整数:"<。 cout<<"较小实数:"<。 return 0。 }

【8.14】写出下面程序的运行结果。 #include template class Sample{ T d。 public:

Sample(){}

Sample(T i){d=i。}

void disp(){cout<<"d="<。}

friend Sampleoperator+(Samples1,Samples2) {

Sampletmp。

55 / 72


tmp.d=s1.d+s2.d。 return tmp。 } }。

void main() {

Samples1(2),s2(3),s3。

Samples4(2.5),s5(8.4),s6。 s3=s1+s2。 s6=s4+s5。 s3.disp()。 s6.disp()。 }

【8.15】写出下面程序的运行结果。 #include using namespace std。 class coord {int x,y。 public:

coord(int x1,int y1){x=x1。y=y1。} int getx(){return x。} int gety(){return y。} int operator<(coord& c)。 }。

int coord::operator<(coord& c) { if(x if(y return 1。 return 0。 }

template

obj& min(obj& o1,obj& o2) {

if(o1 return o1。 return o2。 }

int main() {

coord cl(5,12)。 coord c2(3,16)。

coord c3=min(cl,c2)。

cout<<"最小的坐标:("<。 double d1=2.99。

56 / 72


double d2=3.48。

cout<<"最小的数:"<。 return 0。 }

【8.16】指出下列程序中的错误,并说明原因。 #include using namespace std。

template //模板声明,其中为T类型参数 class Compare{ //类模板名为Compare public:

Compare(T a, T b) { x=a。 y=b。}

T min()。 private:

T x,y。 }。

template T Compare::min() { return (x。 }

int main() {

Compare com1(3,7)。

cout<<"其中的最小值是:"<< com1.min()<。 return 0。 }

【解】

在类模板体外定义成员函数min时“T Compare::min()”是错误的,应在成员函数名前缀上“类名<类型参数>::”, 应该将此语句改为:

T Compare::min()

主函数中语句“Compare com1(3,7)。”是错误的,因为首先要将模板实例化,才能由模板生成对象。应该将此语句改为:

Compare com1(3,7)。 修改后,正确的程序如下: #include using namespace std。

template //模板声明,其中为T类型参数 class Compare{ //类模板名为Compare public:

Compare(T a, T b) { x=a。 y=b。}

T min()。 private: T x,y。

57 / 72


}。

template T Compare::min() { return (x。 }

int main()

{ Compare com1(3,7)。

cout<<"其中的最小值是:"<< com1.min()<。 return 0。 }

程序的运行结果是: 其中的最小值是:3

【8.17】已知下列主函数 int main()

{cout<。 cout<。 cout<。

return 0。 }

设计一个求三个数中最小者的函数模板,并写出调用此函数模板的完整程序。 【解】

求三个数中最小者的函数模板如下: template

Type min(Type a,Type b,Type c) { a= (a。 return (a。 }

完整的程序如下: #include using namespace std。

template

Type min(Type a,Type b,Type c) //声明函数模板 { a= (a。 return (a。 }

int main()

{ cout<。

cout<。 cout<。 return 0。 }

【8.18】编写一个函数模板,求数组中的最大元素,并写出调用此函数模板的完整程序,使得函数调用时,数组的类型可以是整数也可以是双精度类型。

【解】 实现本题功能的程序如下:

58 / 72


#include using namespace std。

template //函数模板 Type max(Type *Array,int size) { int i,j=0。

for (i=1。i。i++) if (Array[i]>Array[j]) { j=i。 }

return Array[j]。

}

int main()

{ int intArray[]={11,12,13,14,7,8,9}。

double doubleArray[]={11.2,12.3,13.2,14.5,14.8,8.7,9.3}。 cout<。 cout<。

return 0。 }

【8.19】编写一个函数模板,使用冒泡排序将数组内容由小到大排列并打印出来,并写出调用此函数模板的完整程序,使得函数调用时,数组的类型可以是整数也可以是双精度型。

【解】 实现本题功能的程序如下: #include template

void sort(Type *Array,int size) { int i,j。

for (i=0。i。i++) for (j=0。j。j++) if (Array[j]>Array[j+1]) { Type temp= Array[j]。 Array[j]=Array[j+1]。 Array[j+1]=temp。 }

for (i=0。i<=size-1。i++) cout<。 cout<。 }

int main()

{ int intArray[]={11,12,13,14,7,8,9}。

double doubleArray[]={11.2,12.3,13.2,14.5,14.8,8.7,9.3}。 sort(intArray,7)。 sort(doubleArray,7)。 return 0。 }

【8.20】建立一个用来实现求三个数和的类模板(将成员函数定义在类模板的内部),并

59 / 72


写出调用此类模板的完整程序。

【解】 实现本题功能的程序如下: #include using namespace std。

template // 模板声明,其中为T类型参数 class Sum{ // 类模板名为Sum public:

Sum(T a,T b,T c) { x=a。 y=b。 z=c。

}

T add()

{ return x+y+z。

}

private:

T x,y,z。 }。

int main()

{ Sum s1(3,7,9)。

//用类模板定义对象s1,此时T被int替代

Sum s2(12.34,56.78,67.89)。

//用类模板定义对象s2,此时T被double替代

cout<<"三个整数的和是:"<。 cout<<"三个双精度数的和是:"<。 return 0。 }

【8.21】将8.20题改写为在类模板外定义各成员函数。 【解】 实现本题功能的程序如下: #include using namespace std。

template //模板声明,其中为T类型参数 class Sum{ //类模板名为Sum public:

Sum(T a,T b,T c)。 //声明构造函数的原型

T add()。 //声明成员函数add的原型 private:

T x,y,z。 }。

template //模板声明

Sum::Sum(T a, T b,T c)//在类模板体外定义构造函数 { x=a。 y=b。 z=c。 }

template //模板声明

T Sum:: add() //在类模板体外定义成员函数add,返回类型为T { return x+y+z。

60 / 72


}

int main()

{ Sum s1(3,7,9)。 //用类模板定义对象s1,此时T被int替代 Sum s2(12.34,56.78,67.89)。

//用类模板定义对象s2,此时T被double替代

cout<<"三个整数的和是:"<。 cout<<"三个双精度数的和是:"<。 return 0。 }



第9章 C++的输入和输出



【9.7】

#include #include using namespace std。 int main() { int i=7890。

cout<。 cout<。 return 0。 }

以上程序运行的结果是( ) 。 A)7890 7890 B)7890 7890 C)7890 7890 D)以上都不对

【9.8】

#include using namespace std。 int main() {int i=100。

cout.setf(ios::hex)。 cout<。 cout<。

cout.setf(ios::dec)。 cout<。

return 0。 }

以上程序运行的结果是( ) 。

61 / 72


A) 64 100 64 B) 64 64 64 C) 64 64 100 D) 64 100 100

【9.17】如果输入是abcdefgh,希望输出abcd efgh。请填写程序中width的宽度。 #include #include using namespace std。 int main()

{ char buffer1[10],buffer2[10]。 cin.width( )。

cin>>buffer1>>buffer2。 cout.width( )。

cout<。 return 0。 }

【9.18】在下划线填上适当的语句,实现Stock类的输入输出运算符重载。 #include #include class Stock{ public:

private:

char Stockcode[7]。 // 股票代码 char Stockname[20]。 // 股票名称 float price。 // 现价 }。

istream & operator>>(istream&in,Stock &st)

{ cout<<"\n请输入股票代码、股票名称和现价:"。 in>>st.Stockcode>>st.Stockname>>st.price。 return in。 }

ostream & operator<<(ostream&out,Stock &st)

{ out<。 return out。 }

int main()

{ Stock stock。 cin>>stock。

cout<。 return 0。 }

【9.19】分别计算5!到9!的值,使用setw()控制“=”左边的数值宽度。

62 / 72


【解】实现本题功能的程序如下: #include #include using namespace std。 double fact(int n)。 int main()

{for(int n=5。n<10。n++)

cout<。 return 0。

}

double fact(int n) {double factor=1。 for(int i=n。 i>=1。 i--)

factor*=i。 return factor。

}

【9.20】编写一个程序,打印2~10之间的数字的自然对数与以10为底的对数。对表进行格式化,使得数字可以在域宽为10的范围内,用5个十进制位置的精度进行右对齐。

【解】实现本题功能的程序如下: #include #include

using namespace std。 int main() { double x。

cout.precision(5)。

cout <<" x ln e log x \n"。 for(x=2.0。 x<= 10.0。 x++) {

cout.width(2)。 cout<。 cout.width(10)。 cout<。 cout.width(10)。

cout<。 }

return 0。 }

【9.21】编写一个程序,将下面的信息表写入文件stock.txt中:

Shen fa zhan 000001 Shang hai qi che 600104 Guang ju neng yuan 000096

【解】 实现本题功能的程序如下: #include

63 / 72


#include using namespace std。 int main()

{ ofstream pout("stock.txt")。 if (!pout )

{ cout<<"Cannot open phone file\n"。 return 1。 }

pout<<"Shen fa zhan 000001\n"。 pout<<"Shang hai qi che 600104\n"。 pout<<"Guang ju neng yuan 000096\n "。 pout.close()。 return 0。 }

【9.22】写一个程序,用于统计某文本文件中单词is的个数。 【解】实现本题功能的程序如下: #include #include using namespace std。 int main()

{ int flag=0,flag2=0。 // flag=0表示前面的字符不是空格

// flag2=0表示前面的字符不是"is"

int sum=0。 //sum记录"is"的个数 char ch。

fstream in("file1.txt",ios::in)。 if(!in)

{ cerr<<"Error open file."。 return 0。 }

while ((ch=in.get())!=EOF) if (ch==' ')

{ if (flag!=1) flag=1 。 } else

{ if (flag==1&&ch=='i') flag2=1。 if (flag2==1&&ch=='s') { sum++。 flag2=0。 }

flag=0。 }

cout<。 //输出"is"的个数 in.close()。

64 / 72


return 1。 }

【9.23】编写一个程序,要求定义in为fstream的对象,与输入文件file1.txt建立关联,文件file1.txt的内容如下:

abcdef ghijklmn

定义out为fstream的对象,与输出文件file2.txt建立关联。当文件打开成功后将file1.txt文件的内容转换成大写字母,输出到file2.txt文件中。

【解】 实现本题功能的程序如下: #include #include using namespace std。 int main()

{ fstream in("file1.txt",ios::in)。 if(!in)

{ cerr<<"Error open file."。 return 1。 }

fstream out("file2.txt",ios::out)。 if (!out)

{ cerr<<"Error open file."。 return 2。 }

char ch。

while ((ch=in.get())!=EOF) out<。 in.close()。 out.close()。 return 0。 }

【9.24】编写一个程序,要求定义in为fstream的对象,与输入文件file1.txt建立关联, 文件file1.txt的内容如下:

aabbcc

定义out为fstream的对象,与输出文件file2.txt建立关联。当文件打开成功后将file1.txt文件的内容附加到file2.txt文件的尾部。运行前file2.txt文件的内容如下:

ABCDEF GHIJKLMN

运行后,再查看文件file2.txt的内容。

【解】 实现本题功能的程序如下: #include #include using namespace std。 int main()

{ ifstream in。

65 / 72


in.open("file1.txt",ios::in)。 if (!in)

{ cerr<<"Error opcn file1.txt."。 return 1。 }

ofstream out。

out.open("file2.txt",ios::app)。 if (!out)

{ cerr<<"Error open file2.txt."。 return 1。 }

char ch。

while ((ch = in.get())!=EOF) out<。 in.close()。 out.close()。 return 0。

}

运行后,查看文件file2.txt的内容如下: ABCDEF GHIJKLMN aabbcc



第10章 异常处理和命名空间

【10.8】写出下面程序的运行结果。 #include

using namespace std。 int f(int )。 int main() { try

{ cout<<"4!="<。 cout<<"-2!="<。 }

catch (int n)

{ cout<<"n="<不能计算n!."<。 cout<<"程序执行结束."<。 }

return 0。 }

int f(int n)

66 / 72


{ if (n<=0) throw n。 int s=1。

for (int i=1。i<=n。i++) s*=i。

return s。 }

【10.9】写出下面程序的运行结果。 #include

using namespace std。 namespace NS1 { void fun()

{ cout<<"NS1:fun"<。 } }

namespace NS2 { void fun()

{ cout<<"NS2:fun"<。 } }

int main() { NS1::fun()。 NS2::fun()。 return 0。 }

第11章 面向对象程序设计方法与实例



【11.1】修改教材中ATM机的程序,增加取款,修改密码的操作。 【解】

修改AccountItem的类声明为: class AccountItem {public:

AccountItem()。

AccountItem(string Anumber, string Password, string Owener,

const double Balance)。

void Display()。

void Read(ifstream& s)。

// the following function was added for inventory update void Write(ofstream& s)。

67 / 72


short CheckNumber(string Anumber)。 string GetNumber()。 string GetPassword()。

void UpdatePassword(string pass)。 //修改密码 void DeductBalance(double pay)。

void SaveAccount(double count)。 //存钱 double GetBalance()。 string GetName()。 short IsNull()。 private:

string m_Anumber。 string m_Password。 string m_Name。 double m_Balance。 。

增加的成员函数为:

void AccountItem::UpdatePassword(string pass) //{ m_Password=pass。 }。

void AccountItem::SaveAccount(double count) //{ m_Balance += count。 }。

主函数修改为:

#include #include #include #include "strclass.h" #include "accitem.h" #include "Accbook.h" int main()

{ ifstream InputStream("Account.in")。 string AccountNo。 string AccPassword。 string newPassword1。 string newPassword2。 double AccountCount。 string ItemName。

double OldAccountbook。 Accountbook MyAccountbook。 AccountItem FoundItem。 string TransactionCode。 string Count。 double SaveCount。

MyAccountbook.LoadAccountbook(InputStream)。

68 / 72

修改密码 存钱count到帐户中 }
cout << "请输入帐号: "。 cin >> AccountNo。

FoundItem = MyAccountbook.FindItem(AccountNo)。 if (FoundItem.IsNull() == true) { cout << "帐号不存在." << endl。 return 0。 }

cout << "请输入口令: "。 cin >> AccPassword。

if (FoundItem.GetPassword()!=AccPassword) { cout << "口令错误!" << endl。 return 0。 }

OldAccountbook=FoundItem.GetBalance()。 cout << "请选择交易代码:" << endl。 cout << "G (取钱)" << endl。 cout << "C (查询余额)" << endl。 cout << "S (存钱)" << endl。 cout << "U (修改密码)" << endl。 cin >> TransactionCode。

if (TransactionCode == "C" || TransactionCode == "c") { cout << "余额是: " << FoundItem.GetBalance()<。 }

else if (TransactionCode == "G" || TransactionCode == "g") { cout << "请选择取钱的数量: "<。 cout << "1 (取100)" << endl。 cout << "2 (取200)" << endl。 cout << "5 (取500)" << endl。 cout << "A (取1000)" << endl。 cout << "B (取2000)" << endl。 cin >> Count。

if (Count=="1") AccountCount=100.。

else if (Count=="2") AccountCount=200.。 else if (Count=="5") AccountCount=500.。 else if (Count=="A") AccountCount=1000.。 else if (Count=="B") AccountCount=2000.。

else { cout<<"选择错误"<。 return 0。} if (OldAccountbook

{ cout<<"存款余额不够!"<。 } else

{ FoundItem.DeductBalance(AccountCount)。 MyAccountbook.UpdateItem(FoundItem)。 cout << "请取钱!" << endl。

ofstream OutputStream("Account.in")。

69 / 72


MyAccountbook.StoreAccountbook(OutputStream)。

} }

else if (TransactionCode == "S"|| TransactionCode == "s") { cout<<"请输入存钱数量:"。 cin>>SaveCount。

FoundItem.SaveAccount(SaveCount)。 MyAccountbook.UpdateItem(FoundItem)。 ofstream OutputStream("Account.in")。

MyAccountbook.StoreAccountbook(OutputStream)。

}

else if (TransactionCode == "U" || TransactionCode == "u") { cout<<"请输入修改后的密码:"。 cin>>newPassword1。

cout<<"请再次输入修改后的密码:"。 cin>>newPassword2。

if (newPassword1==newPassword2)

{ FoundItem.UpdatePassword(newPassword1)。 MyAccountbook.UpdateItem(FoundItem)。 ofstream OutputStream("Account.in")。

MyAccountbook.StoreAccountbook(OutputStream)。 cout<<"密码修改成功!"。 }

else

cout<<"密码修改失败!"。 }

return 0。 }

【11.2】修改网上购书的例子,模拟下定单的操作。每张定单的数据成员如下: class order

{ static int ordercount。 //自动增加定单编号 int orderID。 //订单编号 int buyerID。 //购书人编号 int listcount。 //购书数量

string orderlist[20]。 //记录书号的数组 }

【解】 修改后的程序如下: #include #include "strclass.h" #include "buy.h" #include "book.h" class order { public: order()

70 / 72


{buyerID=0。 ordercount++。

orderID=ordercount。 //定单编号自动加1

listcount=0。 }

void setbuyid(int b_id) { buyerID=b_id。 }

void buy_one_book(string b_id) { orderlist[listcount]=b_id。 listcount++。 }

void display()。 private:

static int ordercount。 //自动增加定单编号 int orderID。 //订单编号 int buyerID。 //购书人编号 string orderlist[20]。 //书号数组 int listcount。 //购书数量 }。

void order::display() { int i。

cout<<"\n定单信息\n\n订单号:"<。 cout<<"购书人编号:"<。 cout<<" 所购图书书号:"。 for (i=0。i。i++) cout<。 cout<。 }

int order::ordercount=0。 void main()

{ int i=0,j=0。

int buyerid,flag。 book *c[2]。

layfolk b1("林小茶",1,"北京",0)。

honoured_guest b2("王遥遥",2,.6,"上海",0)。 member b3("赵红艳",3,5,"广州",0)。 order o1[20]。 //订单数组 buyer *b[3]= {&b1,&b2,&b3}。

book c1("","C++ programing","谭浩强","清华",25)。 book c2("A2","data structure","许天风","北大",20)。 c[0]=&c1。 c[1]=&c2。

cout<<"购书人信息:\n\n"。

71 / 72


for (i=0。i<3。i++)

b[i]->display()。

cout<<"\n图书信息:\n\n"。 for (i=0。i<2。i++) c[i]->display()。 while (j<2)

{ cout<<"\n\n请输入购书人编号:"。 cin>>buyerid。 flag=0。

for (i=0。i<3。i++)

if (b[i]->getid()==buyerid) { flag=1。break。}

if (!flag) { cout<<"编号不存在"<。} else

{b[i]->setpay(c[0]->getprice())。 b[i]->setpay(c[1]->getprice())。

cout<购书人需要付费:"<getpay()<<"\n\n"。 o1[j].setbuyid(b[i]->getid())。

o1[j].buy_one_book(c[0]->getbook_ID())。

o1[j].buy_one_book(c[1]->getbook_ID())。

o1[j].display()。 j++。

} } }



72 / 72


本文来源:https://www.wddqxz.cn/e2c06d64757f5acfa1c7aa00b52acfc788eb9f50.html

相关推荐