文档库 最新最全的文档下载
当前位置:文档库 › C++课后习题

C++课后习题

第一章 c++的初步知识
第二章类和对象
第三章关于类和对象的进一步讨论(静态成员函数、友元函数、构造函数,构造函数的重载;析构函数;类模板)
第四章 运算符重载()
第五章继承与派生
第六章多态性与虚函数
第七章输入输出流
第八章c++工具
谭浩强C++课后习题答案
1.请根据你的了解,叙述C++?的特点。C++?对C有哪些发展?
【解】 略。
2.一个C++的程序是由哪几部分构成的?其中的每一部分起什么作用?
【解】 略。
3.从拿到一个任务到得到最终结果,一般要经过几个步骤?
【解】 略。
4.请说明编辑、编译、连接的作用。在编译后得到的目标文件为什么不能直接运行?
【解】 编译是以源程序文件为单位进行的,而一个完整的程序可能包含若干个程序文件,在分别对它们编译之后,得到若干个目标文件(后缀一般为.obj),然后要将它们连接为一个整体。此外,还需要与编译系统提供的标准库相连接,才能生成一个可执行文件(后缀为.exe)。不能直接运行后缀为.obj的目标文件,只能运行后缀为.exe的可执行文件。
5.分析下面程序运行的结果。

#include <iostream>
using namespace std;
int main( )
{
cout<<" This "<<" is ";
cout<<" a "<<" C++ ";
cout<<"program. " << endl;
return 0;
}

【解】 输出的结果为

ThisisaC++program.



6.分析下面程序运行的结果。

#include <iostream>
using namespace std;
int main( )
{
int a,b,c;
a=10;
b=23;
c=a+b;
cout<<" a+b=";
cout<<c;
cout<<endl;
return 0;
}

【解】 前两个cout语句在输出数据后不换行,第3个cout语句输出一个换行,因此输出的结果为

a+b=33

7.分析下面程序运行的结果。请先阅读程序写出程序运行时应输出的结果,然后上机运行程序,验证自己分析的结果是否正确。以下各题同。

#include <iostream>
using namespace std;
int main( )
{
int a,b,c;
int f(int x,int y,int z);
cin>>a>>b>>c;
c=f(a,b,c);
cout<<c<<endl;
return 0;
}
int f(int x,int y,int z)
{
int m;
if (x<y) m=x;
 else m=y;
if (z<m) m=z;
return(m);
}

【解】 程序的作用是:输入3个整数,然后输出其中值最小的数。在主函数中输入3个整数,然后调用f函数,在f函数中实现找最小的整数,用if语句比较两个数,将小者存放在变量m中,经过两个if语句的比较,m中存放的是3个整数中最小的数。运行情况如下:

1 5 3↙ (输入3个整数)
1 (输出其中最小的数)

8.在你所用的C++系统

上,输入以下程序,进行编译,观察编译情况,如果有错误,请修改程序,再进行编译,直到没有错误,然后进行连接
和运行,分析运行结果。

int main( );
{
int a,b;
c=a+b;
cout >>" a+b=" >> a+b;
}

【解】 上机编译出错,编译出错信息告知在第2行出错,经检查,发现第1行的末尾多了一个分号,编译系统无法理解第2行的花括号,导致报告第2行出错。将第1行的末尾的分号去掉,重新编译,编译出错信息告知在第5行和第6行出错。第5行出错原因是cout未经声明,因为cout不是C++语言提供的系统的关键字,而是输出流的对象,必须使用头文件iostream。第6行出错原因是main是int型函数,应返回一个整型值。将程序改为

#include <iostream>
int main( )
{
int a,b;
c=a+b;
cout >>" a+b=" >> a+b;
return 0;
}

重新编译。编译出错信息告知在第5行和第6行出错。第5行出错原因是变量c未定义,第6行出错原因是cout未经声明,说明#include <iostream>命令行未能起作用,原因是未指明命名空间。将程序改为

#include <iostream>
using namespace std;
int main( )
{
int a,b,c;
c=a+b;
cout>>" a+b=" >>a+b;
return 0;
}
重新编译。编译出错信息告知在第7行出错,经检查,是“>>”用得不当,“>>”是提取运算符,应与cin联合使用,用来从输入流中提取数据,输出时应该用插入运算符“<<”。把两处“>>”都改为“<<”,再重新编译,发现没有error错误,但有两个警告(warning),原因是定义了a和b,但未对它们赋值。应增加赋值语句或输入语句,使a和b获得值,将程序改为

#include <iostream>
using namespace std;
int main( )
{
int a,b,c;
cin>>a>>b;
c=a+b;
cout>>" a+b=" >>a+b;
return 0;
}

重新编译,没有编译错误,能通过编译和连接,可以正常运行,在Visual C++ 6.0环境下运行时屏幕显示如下:

5 9↙
a+b=14Press any key to continue

显然这样的输出不理想,“Press any key to continue”是Visual C++系统在输出了运行结果后自动显示的一个信息,告诉用户“如果想继续工作,请按任何一个键”。当用户按任何一个键后,显示运行结果的窗口消失,屏幕显示回到Visual C++的主窗口,显示出源程序和编译信息。
为了解决以上输出不理想的情况,可以在最后一个输出语句中增加输出一个换行符。最后的程序如下:

#include <iostream>
using namespace std;
int main( )
{
int a,b,c;
cin>>a>>b;
c=a+b;
cout<<"a+b="<<a+b<<endl;
return 0;
}

运行时屏幕显示如下:

5 9↙
a+b=14
Pre

ss any key to continue

这就完成了程序的调试。
这里对本题的调试过程作了比较详细的分析,以便使读者对如何调试程序有比较具体而清晰的了解。需要说明:
(1)编译系统给出的编译出错信息,只是提示性的,引导用户去检查错误,用户必须根据程序的上下文和编译出错信
息,全面考虑,找出真正出错之处。例如编译出错信息通知第2行出错,其实可能是第1行出错。
(2)有时,有的错误开始时未被检查出来并告知用户(例如未定义变量c),由于其他错误未解决,掩盖了这个错误。当解决了其他错误后,这个错误会被检查出来。有时在调试过程中会不断检查出新的错误,这是不奇怪的。一一处理,问题会迎刃而解。
(3)为了说明调试过程,这里全部依靠计算机系统来检查错误,其实有些明显的错误,完全可以由人工查出,这样可以提高调试效率。由人工在纸面或屏幕上检查错误,称为静态查错,用计算机编译系统检查错误,称为动态查错。建议尽量先用静态查错的方法排除错误,只有人工检查不出来的错误才让计算机检查。
9.输入以下程序,进行编译,观察编译情况,如果有错误,请修改程序,再进行编译,直到没有错误,然后进行连接和运行,分析运行结果。

#include <iostream>
using namespace std;
int main( )
{
int a,b;
c=add(a,b)
cout<<"a+b="<<c<<endl;
return 0;
}
int add(int x,int y);
{
z=x+y;
retrun(z);
}

【解】 发现7个错误:
(1)对add函数未声明就调用,应在main函数中对add函数进行声明。
(2)定义add函数时,函数首行末尾不应有分号。
(3)变量c未经定义。
(4)add函数中的变量z未经定义。
(5)第6行末尾少了一个分号。
(6)add函数中的retrun拼写错误,应为return。编译系统把retrun作为未声明的标识符而报错,因为retrun(z)会被认为是函数调用的形式。
(7)变量a和b未被赋值。
改正后的程序如下:

#include <iostream>
using namespace std;
int main( )
{int add(int x,int y);
int a,b,c;
cin >> a >> b;
c=add(a,b);
cout <<" a+b=" << c <<endl;
return 0;
}

int add(int x,int y)
{int z;
z=x+y;
return(z);
}

运行情况如下:

5 8↙
13

10.输入以下程序,编译并运行,分析运行结果。

#include <iostream>
using namespace std;
int main( )
{ void sort(int x,int y,int z);
int x,y,z;
cin >> x >> y >> z;
sort(x,y,z);
return 0;
}
void sort(int x, int y, int z)
{
int temp;
if (x>y) {temp=x;x=y;y=temp;} //{ }内3个语句的作用是将x和y的值互换
if (z<x) cout << z << ',' << x <<

; ',' << y << endl;
else if (z<y) cout << x <<',' << z << ',' << y << endl;
else cout << x << ',' << y << ',' << z << endl;
}

请分析此程序的作用。sort函数中的if语句是一个嵌套的if语句。
运行时先后输入以下几组数据,观察并分析运行结果。

① 3 6 10↙
② 6 3 10↙
③ 10 6 3↙
④ 10,6,3↙

【解】 程序的作用是对输入的3个整数按由小到大的顺序进行排序。sort函数中的第1个if语句的作用是先将x和y
排序,使x小于或等于y。第2个if语句是一个嵌套的if语句,先比较z和x,如果z<x,显然由小到大的顺序应当是z,x,y,按此顺序输出;如果z不小于x,而小于y,显然由小到大的顺序应当是x,z,y,按此顺序输出;如果z既不小于x,又不小于y,显然由小到大的顺序应当是x,y,z,按此顺序输出。
按题目要求分别输入以下几组数据,运行结果如下:

① 3 6 10↙
3,6,10
② 6 3 10↙
3,6,10
③ 10 6 3↙
3,6,10
④ 10,6,3↙
-858993460,-858993460,10

以上是在Visual C++ 6.0环境下运行的情况,前3次运行正常,表明当输入不同的数据时,程序能实现由小到大的排序功能。第4次运行的结果显然不正常,这是由于输入数据时出了问题,本来要求在输入数据时,数据之间以空格或换行相隔,而现在却以逗号相隔,只有第一个整数能正常赋给变量x,第二和第三个数据均无法正常赋给变量y和z,y和z的值来自输入流中相应字节的内容。
11.求2个或3个正整数中的最大数,用带有默认参数的函数实现。
【解】 可以编写出以下程序:

#include <iostream>
using namespace std;
int main( )
{int max(int a,int b,int c=0);
int a,b,c;
cin >> a >> b >> c;
cout << " max(a,b,c)= " << max(a,b,c) << endl;
cout << " max(a,b)= " <<max(a,b) << endl;
return 0;
}

int max(int a,int b,int c)
{if(b>a) a=b;
if(c>a) a=c;
return a;
}

运行情况如下:

13 5 76↙
max(a,b,c)=76 (从3个数中找最大者)
max(a,b)=13 (从前2个数中找最大者)

如果想从3个数中找大者,可以在调用时写成“max(a,b,c)”形式,如果只想从2个数中找大者,则在调用时写成“max(a,b)”形式,此时c自动取默认值0,由于0比任何正整数都小,因此从14,5,0中选最大者和从14,5中选大者的结果是一样的。
12.输入两个整数,将它们按由大到小的顺序输出。要求使用变量的引用。
【解】 可以编写出以下程序:

#include<iostream>
using namespace std;
int main( )
{ v

oid change(int &,int &);
int a,b;
cin>>a>>b;
if(a<b) change(a,b); //如果a<b,使a和b的值互换
cout<<"max="<<a<<" min="<<b<<endl;
return 0;
}

void change(int &r1,int &r2) //函数的作用是使r1与r2互换
{ int temp;
temp=r1;
r1=r2;
r2=temp;
}

运行情况如下:

12 67↙
max=67 min=12

13.对3个变量按由小到大顺序排序,要求使用变量的引用。
【解】 可以编写出以下程序:

#include <iostream>
using namespace std;
int main( )
{void sort(int &,int &,int &);
int a,b,c,a1,b1,c1;
cout<<" Please enter 3 integers:";
cin>>a>>b>>c;
a1=a;b1=b;c1=c;
sort(a1,b1,c1);
cout<<a<<" "<<b<<" "<<c<<" in sorted order is ";
cout<<a1<<" "<<b1<
<" "<<c1<<endl;
return 0;
}
void sort(int &i,int &j,int &k)
{ void change(int &,int &);
if (i>j) change(i, j);
if (i>k) change(i, k);
if (j>k) change(j, k);
}
void change(int &x,int &y)
{ int temp;
temp=x;
x=y;
y=temp;
}

运行情况如下:

Please enter 3 integers:23 67 -55↙
23 67 –55 in sorted order is –55 23 67

这个程序很容易理解,不易出错。由于在调用sort函数时虚实结合使形参i,j,k成为实参a1,b1,c1的引用(别名),因此通过调用函数sort(a1,b1,c1)既实现了对i,j,k排序,也就同时实现了对a1,b1,c1排序。同样,执行change(i,j)函数,可以实现对实参i和j的互换。
14.编一程序,将两个字符串连接起来,结果取代第一个字符串。要求用string方法。
【解】 可以编写出以下程序:

#include <iostream>
#include <string> //程序中若使用字符串变量,必须包含头文件string
using namespace std;
int main( )
{ string s1= " week ",s2= " end ";
cout << " s1= " << s1 << endl;
cout << "s2=" << s2 << endl;
s1=s1+s2;
cout<<" The new string is: "<<s1<<endl;
return 0;
}

运行情况如下:

s1=week
s2=end
The new string is: weekend

15.输入一个字符串,把其中的字符按逆序输出。如输入LIGHT,输出THGIL。要求用string方法。
【解】 可以编写出以下程序:

#include <iostream>
#include <string>
using namespace std;
int main( )
{ string str; //定义字符串变量str
int i,n;
char temp; //定义字符变量temp
cout<<" please input a string: ";
cin>>str; //输入一个字符串赋给字符串变量str
n=str.size( ); //测量str的

长度n
for(i=0;i<n/2;i++) //使str中的字符对称互换
{temp=str[i];str[i]=str[n-i-1];str[n-i-1]=temp;}
cout << str << endl;
return 0;
}

运行情况如下:

please input a string:
LIGHT↙
THGIL

注意:输入的字符串中不能含有空格。
16.有5个字符串,要求将它们按由小到大的顺序排列,用string方法。
【解】 可以编写出以下程序:

#include <iostream>
#include <string>
using namespace std;
int main( )
{ int i;
string str[5]={" BASIC"," C"," FORTRAN"," C++","PASCAL"};
void sort(string [ ]);
sort(str); //对字符串排序
cout<<" the sorted strings : "<<endl;
for(i=0;i<5;i++)
cout<<str[i]<<" "; //按已排好的顺序输出字符串
cout<<endl;
return 0;
}

void sort(string s[ ])
{int i, j;
string t;
for (j=0; j<5; j++)
for(i=0; i<5-j; i++)
if (s[i]>s[i+1])
{t=s[i];s[i]=s[i+1];s[i+1]=t;}
}

运行结果如下:

the sorted strings :
BASIC C C++ FORTRAN PASCAL

17.编一个程序,用同一个函数名对n个数据进行从小到大排序,数据类型可以是整
型、单精度型、双精度型。用重载函数实现。
【解】 可以编写出以下两个程序:
(1)建立3个函数,分别用于处理整型、单精度型、双精度型数据的排序,在3个函数中都采用选择法排序方法。

#include <iostream>
#include <string>
using namespace std;
int main( )
{
long a[5]={10100,-123567, 1198783,-165654, 3456};
int b[5]={1,9,0,23,-45};
float c[5]={2.4, 7.6, 5.5, 6.6, -2.3 };
void sort(long [ ]);
void sort(int [ ]);
void sort(float [ ]);
sort(a);
sort(b);
sort(c);
return 0;
}

void sort(long a[ ])
{int i, j;
long t;
for (j=0; j<5; j++)
for(i=0;i<5-j;i++)
if (a[i]>a[i+1])
{t=a[i];a[i]=a[i+1];a[i+1]=t;}
cout<<" the sorted numbers : "<<endl;
for(i=0;i<5;i++)
cout<<a[i]<< " ";
cout<<endl<<endl;
}

void sort(int a[ ])
{int i, j, t;
for (j=0; j<5; j++)
for(i=0;i<5-j;i++)
if (a[i]>a[i+1])
{t=a[i];a[i]=a[i+1];a[i+1]=t;}
cout<<" the sorted numbers : "<<endl;
for(i=0;i<5;i++)
cout<<a[i]<< " ";
cout<<endl<<endl;
}

void sort(float a[ ])
{int i, j;
float t;
for (j=0;j<5;j++)
for(i=0;i<5-j;i++)
if (a[i]>a[i+1])
{t=a[i];a[i]=a[i+1];a[i+1]=t;}
cout<<" the sorted numbers : "<<endl;
for(i=0;i<5;i++)
cout<<a[i]<< " ";
cout<<endl<<endl;
}

运行结果如下:

the sorted numbers :
-123567 -165654 10100 3456 1198783 (长整型数据排序)

the sorted numbers : (

整型数据排序)
-45 0 1 9 23

the sorted numbers :
-2.3 2.4 5.5 6.6 7.6 (单精度型数据排序)

(2)在第1种方法中,3个函数的函数体基本上是相同的,都是采用选择法排序,在下面的程序中,3个函数的函数体不全相同,前两个函数采用选择法排序,最后一个函数采用起泡法排序。

#include <iostream>
#include <string>
using namespace std;
int main( )
{ long a[5]= {10100,-123567, 1198783,-165654, 3456};
int b[5]={1,9,0,23,-45};
float c[5]={2.4, 7.6, 5.5, 6.6, -2.3 };
void sort(int [ ]);
void sort(float [ ]);
void sort(long [ ]);
sort(a); //对长整型数据排序
sort(b); //对整型数据排序
sort(c); //对单精度型数据排序
return 0;
}

void sort(long a[ ]) //对长整型数据用选择法排序的函数
{int i,j,min;
long t;
for(i=0;i<5;i++)
{min=i;
for (j=i+1;j<5;j++)
if(a[min]>a[j]) min=j;
{t=a[i]; a[i]=a[min]; a[min]=t; }
cout<<" the sorted numbers : "<<endl;
for(i=0;i<5;i++)
cout<<a[i]<< " ";
cout<<endl<<endl;
}


void sort(int a[ ]) //对整型数据用选择法排序的函数
{int i, j, t;
for (j=0; j<5; j++)
for(i=0;i<5-j;i++)
if (a[i]>a[i+1])
{t=a[i];a[i]=a[i+1];a[i+1]=t;}
cout<<" the sorte
d numbers : "<<endl;
for(i=0;i<5;i++)
cout<<a[i]<< " ";
cout<<endl<<endl;
}

void sort(float a[ ]) //对单精度型数据用起泡法排序的函数
{int i, j;
float t;
for (j=0;j<5;j++)
for(i=0;i<5-j;i++)
if (a[i]>a[i+1])
{t=a[i];a[i]=a[i+1];a[i+1]=t;}
cout<<" the sorted numbers : "<<endl;
for(i=0;i<5;i++)
cout<<a[i]<< " ";
cout<<endl<<endl;
}

运行结果如下:

the sorted numbers :
-123567 -165654 10100 3456 1198783 (长整型数据排序结果)

the sorted numbers : (整型数据排序结果)
-45 0 1 9 23

the sorted numbers :
-2.3 2.4 5.5 6.6 7.6 (单精度型数据排序结果)

对比两种方法,可以看到,并不要求重载函数的函数体相同,在本例中,采用不同的排序方法,结果是相同的。从理论上说,重载的函数可以用来实现完全不同的功能,但是应该注意:同一个函数名最好用来实现相近的功能,而不要用来实现完全不相干的功能,以方便用户理解和使用。
18.对第17题改用函数模板实现。并与17题程序进行对比分析。

#include <iostream>
#include <string>
using namespace std;
template <typename T >
void sort(T a[ ])

//函数模板,采用选择法排序
{int i, j, min;
T t;
for(i=0;i<5;i++)
{min=i;
for (j=i+1; j<5; j++)
if(a[min]>a[j]) min=j;
t=a[i]; a[i]=a[min]; a[min]=t;
}
cout<<" the sorted numbers : "<<endl;
for(i=0;i<5;i++)
cout<<a[i]<< " ";
cout<<endl<<endl;
}

int main( )
{ long a[5]={10100,-123567, 1198783,-165654, 3456};
int b[5]={1,9,0,23,-45};
float c[5]={2.4, 7.6, 5.5, 6.6, -2.3 };
sort(a);
sort(b);
sort(c);
return 0;
}

运行结果如下:

the sorted numbers :
-123567 -165654 10100 3456 1198783 (长整型数据排序)

the sorted numbers : (整型数据排序)
-45 0 1 9 23

the sorted numbers :
-2.3 2.4 5.5 6.6 7.6 (单精度型数据排序)

对比第17题和18题,可以看到,如果重载函数的函数体基本相同的话,用函数模板显然更方便,可以压缩程序篇幅,使用方便。
第二章 类和对象
XT2-6-1 需要求3个长方柱的体积,请编写一个基于对象的程序。数据成员包括length长、width宽、height高。要求用成员函数实现以下功能:
(1)由键盘分别输入3个长方柱的长、宽、高;
(2)计算长方柱的体积;
(3)输出3个长方柱的体积。
请编程序,上机调试并运行。
XT2-6-1
#include <iostream>
using namespace std;
class Box
{public:
void get_value();
float volume();
void display();
public:
float lengh;
float width;
float height;
};

void Box::get_value()
{ cout<<"please input lengh, width,height:";
cin>>lengh;
cin>
>width;
cin>>height;
}

float Box::volume()
{ return(lengh*width*height);}

void Box::display()
{ cout<<volume()<<endl;}

int main()
{Box box1,box2,box3;
box1.get_value();
cout<<"volmue of box1 is ";
box1.display();
box2.get_value();
cout<<"volmue of box2 is ";
box2.display();
box3.get_value();
cout<<"volmue of box3 is ";
box3.display();
return 0;
}
XT2-6-2.也可以将volume函数定义为void类型,它也是用来计算体积,但它不返回体积的值,,另设一个数据成员vol用来存放体积的值,程序改写如下:
#include <iostream>
using namespace std;
class Box
{public:
void get_value();
void volume();
void display();
public:
float lengh;
float width;
float height;
float vol;
};

void Box::get_value()
{ cout<<"please input lengh, width,height:";
cin>>lengh;
cin>>width;
cin>>height;
}

void Box::volume()
{ vol=lengh*width*height;}

void Box::display()
{ cout<<vol<<endl;}

int main()
{Box box1,box2,box3;
box1.get_value();
box1.volume();
cout<<"volmue of box1 is ";
box1.display();
box2.get_value(

);
box2.volume();
cout<<"volmue of box2 is ";
box2.display();
box3.get_value();
box3.volume();
cout<<"volmue of box3 is ";
box3.display();
return 0;
}
XT3-4.建立一个对象数组,内放5个学生的数据,用指针指向数组首元素,输出第1,3,5个学生的数据

#include <iostream>
using namespace std;
class Student
{public:
Student(int n,float s):num(n),score(s){}
void display();
private:
int num;
float score;
};

void Student::display()
{cout<<num<<" "<<score<<endl;}

int main()
{Student stud[5]={
Student(101,78.5),Student(102,85.5),Student(103,98.5),
Student(104,100.0),Student(105,95.5)};
Student *p=stud;
for(int i=0;i<=2;p=p+2,i++)
p->display();
return 0;
}

XT3-5.CPP建立一个对象数组,内放5个学生的数据(学号,成绩),设立一个函数max,用指向对象的指针作函数参数。在max函数中找出五个学生中成绩及最高者并输出其学号
#include <iostream>
using namespace std;
class Student
{public:
Student(int n,float s):num(n),score(s){}
int num;
float score;
};

void main()
{Student stud[5]={
Student(101,78.5),Student(102,85.5),Student(103,98.5),
Student(104,100.0),Student(105,95.5)};
void max(Student* );
Student *p=&stud[0];
max(p);
}

void max(Student *arr)
{float max_score=arr[0].score;
int k=0;
for(int i=1;i<5;i++)
if(arr[i].score>max_score) {max_score=arr[i].score;k=i;}
cout<<arr[k].num<<" "<<max_score<<endl;
}

XT3-9.CPP商店销售某一商品,商店每天公布统一的折扣(discount)。同时允许销售人员
在销售时灵活掌握售价(price),在此基础上,对一此购10件以上者,还可以享受9.8折优惠,现已知当天3名销售员销售情况为:
售货员号(num) 售货件数(quantity)售货
单价(price)
101 5 23.5
102 12 24.56
103 100 21.5
请编程序计算出当日此商品的总销售数sum,以及每件商品的平均售价。要用静态数据成员和静态成员函数。
#include <iostream>
using namespace std;
class Product
{public:
Product(int n,int q,float p):num(n),quantity(q),price(p){};
void total();
static float average();
static void display();

private:
int num;
int quantity;
float price;
static float discount;
static float sum;
static int n;
};

void Product::total()
{float rate=1.0;
if(quantity>10) rate=0.98*rate;
sum=sum+quantity*price*rate*(1-discount);
n=n+quantity;
}

void Product::display()
{cout<<sum<<endl;
cout<<average()<<endl;
}

float Product::average()
{return(sum/n);}


float Product::discount=0.05;
float Product::sum=0;
int Product::n=0;

int main()
{
Product Prod[3]

={
Product(101,5,23.5),Product(102,12,24.56),Product(103,100,21.5)
};
for(int i=0;i<3;i++)
Prod[i].total();
Product::display();
return 0;
}
运算符重载
XT4-1.CPP定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。将运算符函数重载为非成员、非友元的普通函数,编写程序,求两个复数之和
#include <iostream>
using namespace std;
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
double get_real();
double get_imag();
void display();
private:
double real;
double imag;
};

double Complex::get_real()
{return real;}

double Complex::get_imag()
{return imag;}

void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

Complex operator + (Complex &c1,Complex &c2)
{
return Complex(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_imag());
}

int main()
{Complex c1(3,4),c2(5,-10),c3;
c3=c1+c2;
cout<<"c3=";
c3.display();
return 0;
}
XT4-2.CPP定义一个复数类Complex,重载运算符“+”,“-”,“*”,"/"使之能用于复数的加、减、乘。除。运算符重载函数最为Complex类的成员函数,编程序,分别求两个复数之和、差、积和商。

#include <iostream>
using namespace std;
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator+(Complex &c2);
Complex operator-(Complex &c2);
Complex operator*(Complex &c2);
Complex operator/(Complex &c2);
void display();
private:
double real;
double imag;
};

Complex Complex::operator+(Complex &c2)
{Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;}

Complex Complex::operator-(Complex &c2)
{Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;}

Complex Complex::operator*(Com
plex &c2)
{Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;}

Complex Complex::operator/(Complex &c2)
{Complex c;
c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;}

void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

int main()
{Complex c1(3,4),c2(5,-10),c3;
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
return 0;
}
XT4-3.CPP定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。

例如:c1+c2,i+c1,c1+i均合法(设i为整数,c1,c2为复数)。编程序,分别求俩个复数之和,整数和复数之和。

#include <iostream> //用VC++时改为∶ #include <iostream.h>
using namespace std; //用VC++时为取消此行
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator+(Complex &c2);
Complex operator+(int &i);
friend Complex operator+(int&,Complex &);
void display();
private:
double real;
double imag;
};

Complex Complex::operator+(Complex &c)
{return Complex(real+c.real,imag+c.imag);}

Complex Complex::operator+(int &i)
{return Complex(real+i,imag);}

void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

Complex operator+(int &i,Complex &c)
{return Complex(i+c.real,c.imag);}

int main()
{Complex c1(3,4),c2(5,-10),c3;
int i=5;
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=i+c1;
cout<<"i+c1=";
c3.display();
c3=c1+i;
cout<<"c1+i=";
c3.display();
return 0;
}
XT4-4.CPP有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+“,使之能用于矩阵相加。如c=a+b.

#include <iostream>
using namespace std;
class Matrix //定义Matrix类
{public:
Matrix(); //默认构造函数
friend Matrix operator+(Matrix &,Matrix &); //重载运算符“+”
void input(); //输入数据函数
void display(); //输出数据函数
private:
int mat[2][3];
};

Matrix::Matrix() //定义构造函数
{for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
mat[i][j]=0;
}

Matrix operator+(Matrix &a,Matrix &b) //定义重载运算符“+”函数
{Matrix c;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
{c.mat[i][j]=a.mat[i][j]+b.mat[i][j];}
return c;
}
void Matrix::input() //定义输入数据函数
{cout<<"input value of matrix:"<<end
l;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
cin>>mat[i][j];
}

void Matrix::display() //定义输出数据函数
{for (int i=0;i<2;i++)
{for(int j=0;j<3;j++)
{cout<<mat[i][j]<<" ";}
cout<<endl;}
}

int main()
{Matrix a,b,c;
a.input();
b.input();
cout<<endl<<"Matrix a:"<<endl;
a.display();
cout<<endl<<"Matrix b:"<<endl;
b.display();
c=a+b; //用重载运算符“+”实现两个矩阵相加
cout<<endl<<"Matrix c = Matrix a + Matrix b :

"<<endl;
c.display();
return 0;
}
XT4-5.CPP在上题的基础上,重载流插入运算符“<<”和流提取运算符“>>”使之能用于该矩阵的输入和输出
#include <iostream.h>
//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][3];
};

Matrix::Matrix()
{for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
mat[i][j]=0;
}

Matrix operator+(Matrix &a,Matrix &b)
{Matrix c;
for(int i=0;i<2;i++)
for(int j=0;j<3;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:"<<endl;
for(int i=0;i<2;i++)
for(int j=0;j<3;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<3;j++)
{out<<m.mat[i][j]<<" ";}
out<<endl;}
return out;
}

int main()
{ Matrix a,b,c;
cin>>a;
cin>>b;
cout<<endl<<"Matrix a:"<<endl<<a<<endl;
cout<<endl<<"Matrix b:"<<endl<<b<<endl;
c=a+b;
cout<<endl<<"Matrix c = Matrix a + Matrix b :"<<endl<<c<<endl;
return 0;
}
XT4-6.CPP请编写程序,处理一个复数与一个double数相加的运算,结果存放在一个double型的变量dl中,输出dl的值,再以复数的形式输出此值。定义complex(复数)类在成员函数中包含重载类型转换运算符:operator double(){return real;}

#include <iostream>
using namespace std;
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r){real=r;imag=0;}
Complex(double r,double i){real=r;imag=i;}
operator double(){return real;}
void display();
private:
double real;
double imag;
};

void Complex::display()
{cout<<"("<<real<<", "<<imag<<")"<<endl;}

int main()
{Complex c1(3,4),c2;
double d1;
d1=2.5+c1;
cout<<"d1="<<d1<<endl;
c2=Complex(d1);
cout<<"c2=";
c2.display();
return 0;
}
XT4-7.CPP定义一个Teacher(教师)类和一个Student(学生)类,二者有一部分数据成员是相同的,例如num(号码),name(姓名),sex(性别)。编写程序,将一个对象学生转换为教师类,只将以上3个相同的数据成员移植过去。可以设想为:一位学生大学毕业了,留校担任老师,他原有部分
数据对现在的教师身份来说仍然有用的,应当保留并作为其教师的数据的一部分。
#include <iostream>
using namespace std;

class Student
{public:
Student(int,char[],char,float);
int get_num(){return num;}
char * get_name(){return name;}
char get_sex(){return sex;}
void display()
{cout<<"num:"<<num<<"\nname:"<<name<<"\nsex:"<<sex<<"\nscore:"<<score<<"\n\n";}
private:
int num;
char name[20];
char sex;
float score;
};

Student::Student(int n,char nam[],char s,float so)
{num=n;
strcpy(name,nam);
sex=s;
score=so;
}

class Teacher
{public:
Teacher(){}
Teacher(Student&);
Teacher(int n,char nam[],char sex,float pay);
void display();
private:
int num;
char name[20];
char sex;
float pay;
};

Teacher::Teacher(int n,char nam[],char s,float p)
{num=n;
strcpy(name,nam);
sex=s;
pay=p;
}

Teacher::Teacher(Student& stud)
{num=stud.get_num();
strcpy(name,stud.get_name());
sex=stud.get_sex();
pay=1500;}

void Teacher::display()
{cout<<"num:"<<num<<"\nname:"<<name<<"\nsex:"<<sex<<"\npay:"<<pay<<"\n\n";}


int main()
{Teacher teacher1(10001,"Li",'f',1234.5),teacher2;
Student student1(20010,"Wang",'m',89.5);
cout<<"student1:"<<endl;
student1.display();
teacher2=Teacher(student1);
cout<<"teacher2:"<<endl;
teacher2.display();
return 0;
}
继承与派生
XT5-9.CPP分别定义Teacher(教师类)和Cardre(干部类),采用多重继承方式由这两个类派生出新类Teacher_Cardre(教师兼干部类)。要求:
(1)在两个基类中都包含姓名、年龄、性别、地址、电话等数据成员;
(2)在Teacher类中还包含数据成员,职称;在Cadre类中还包含数据成员,职务,在Teacher_Cadre类中还包含数据成员,工资;
(3)对两个基类中的姓名、年龄、性别、地址、电话等数据成员用相同的名字,在引用这些数据成员时,指定作用域;
(4)在类体中声明成员函数,在类外定义成员函数(使用多文件编程!)
(5)在派生类Teacher_Cadre的成员函数show中调用Teacher类中的display函数,输出姓名、年龄、性别、职称、地址、电话,然后用cout语句输出职务和工资。

#include<string>
#include <iostream>
using namespace std;
class Teacher
{public:
Teacher(string nam,int a,char s,string tit,string ad,string t);
void display();
protected:
string name;
int age;
char sex;
string title;
string addr;
string tel;
};

Teacher::Teacher(string nam,int a,char s,string tit,string ad,string t):
name(nam),age(a),sex(s),title(tit),addr(ad),tel(t){ }
void Teacher::display()
{cout<<"name:"<<name<<endl;
cout<<"age"<<age<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"title:"

<<title<<endl;
cout<<"address:"<<addr<<endl;
cout<<"tel:"<<tel<<endl;
}

class Cadr
e
{public:
Cadre(string nam,int a,char s,string p,string ad,string t);
void display();
protected:
string name;
int age;
char sex;
string post;
string addr;
string tel;
};

Cadre::Cadre(string nam,int a,char s,string p,string ad,string t):
name(nam),age(a),sex(s),post(p),addr(ad),tel(t){}

void Cadre::display()
{cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"post:"<<post<<endl;
cout<<"address:"<<addr<<endl;
cout<<"tel:"<<tel<<endl;
}

class Teacher_Cadre:public Teacher,public Cadre
{public:
Teacher_Cadre(string nam,int a,char s,string tit,string p,string ad,string t,float w);
void show( );
private:
float wage;
};

Teacher_Cadre::Teacher_Cadre(string nam,int a,char s,string t,string p,string ad,string tel,float w):
Teacher(nam,a,s,t,ad,tel),Cadre(nam,a,s,p,ad,tel),wage(w) {}
void Teacher_Cadre::show( )
{Teacher::display();
cout<<"post:"<<Cadre::post<<endl;
cout<<"wages:"<<wage<<endl;
}

int main( )
{Teacher_Cadre te_ca("Wang-li",50,'f',"prof.","president","135 Beijing Road,Shanghai","(021)61234567",1534.5);
te_ca.show( );
return 0;
}
XT6-4.CPP写一个程序,定义抽象基类Shape,由它派生出3个派生类,Cirle(圆形、Rectangle(矩形)、Triangle(三角形)。用一个函数printArea 分别输出以上三者的面积,3个图形的数据在定义对象时给定
#include <iostream>
using namespace std;
//定义抽象基类Shape
class Shape
{public:
virtual double area() const =0; //纯虚函数
};

//定义Circle类
class Circle:public Shape
{public:
Circle(double r):radius(r){} //结构函数
virtual double area() const {return 3.14159*radius*radius;}; //定义虚函数
protected:
double radius; //半径
};

//定义Rectangle类
class Rectangle:public Shape
{public:
Rectangle(double w,double h):width(w),height(h){} //结构函数
virtual double area() const {return width*height;} //定义虚函数
protected:
double width,height; //宽与高
};

class Triangle:public Shape
{public:
Triangle(double w,double h):width(w),height(h){} //结构函数
virtual double area() const {return 0.5*width*height;} //定义虚函数
protected:
double width,height; //宽与高
};

//输出面积的函数
void pr

intArea(const Shape &s)
{cout<<s.area()<<endl;} //输出s的面积

int main()
{
Circle circle(12.6); //建立Circle类对象circle
cout<<"area of circle =";
printArea(circle); //输出circle的面积
Rectangl
e rectangle(4.5,8.4); //建立Rectangle类对象rectangle
cout<<"area of rectangle =";
printArea(rectangle); //输出rectangle的面积
Triangle triangle(4.5,8.4); //建立Triangle类对象
cout<<"area of triangle =";
printArea(triangle); //输出triangle的面积
return 0;
}
多态性与虚函数
XT6-5.CPP写一个程序,定义抽象基类Shape,由它派生出5个派生类,Cirle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形)。用虚函数分别计算几种图形面积,并求他们的和。要求用基类指针数组,使它的每一个元素指向一个派生类对象。


#include <iostream>
using namespace std;
//定义抽象基类Shape
class Shape
{public:
virtual double area() const =0; //纯虚函数
};

//定义Circle(圆形)类
class Circle:public Shape
{public:
Circle(double r):radius(r){} //结构函数
virtual double area() const {return 3.14159*radius*radius;}; //定义虚函数
protected:
double radius; //半径
};

//定义Square(正方形)类
class Square:public Shape
{public:
Square(double s):side(s){} //结构函数
virtual double area() const {return side*side;} //定义虚函数
protected:
double side;
};

//定义Rectangle(矩形)类
class Rectangle:public Shape
{public:
Rectangle(double w,double h):width(w),height(h){} //结构函数
virtual double area() const {return width*height;} //定义虚函数
protected:
double width,height; //宽与高
};

//定义Trapezoid(梯形)类
class Trapezoid:public Shape
{public:
Trapezoid(double t,double b,double h):top(t),bottom(t),height(h){} //结构函数
virtual double area() const {return 0.5*(top+bottom)*height;} //定义虚函数
protected:
double top,bottom,height; //上底、下底与高
};

//定义Triangle(三角形)类
class Triangle:public Shape
{public:
Triangle(double w,double h):width(w),height(h){} //结构函数
virtual double area() const {return 0.5*width*height;} //定义虚函数
protected:
do

uble width,height; //宽与高
};

int main()
{
Circle circle(12.6); //建立Circle类对象circle
Square square(3.5); //建立Square类对象square
Rectangle rectangle(4.5,8.4); //建立Rectangle类对象rectangle
Trapezoid trapezoid(2.0,4.5,3.2);
//建立Trapezoid类对象trapezoid
Triangle triangle(4.5,8.4); //建立Triangle类对象
Shape *pt[5]={&circle,&square,&rectangle,&trapezoid,&triangle};
//定义基类指针数组pt,使它每一个元素指向一个派生类对象
double areas=0.0; //areas为总面积
for(int i=0;i<5;i++)
{areas=areas+pt[i]->area();}
cout<<"totol of all areas="<<areas<<endl; //输出总面积
return 0;
}
输入输出流
XT7-1-1.CPP输入三角形的三边a,b,c,计算三角形面积的公式是area=s(s-a)(s-b)(s-c)根号下s=a+b+c/2,构成三角形三边的条件是:a+b>c,b+c>a,c+a>b编写程序输入abc是否满足以上条件 ,如不满足由cerr输出有关错误信息。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{double a,b,c,s,area;
cout<<"please input a,b,c:";
cin>>a>>b>>c;
if (a+b<=c)
cerr<<"a+b<=c,error!"<<endl;
else if(b+c<=a)
cerr<<"b+c<=a,error!"<<endl;
else if (c+a<=b)
cerr<<"c+a<=b,error!"<<endl;
else
{s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"area="<<area<<endl;}
return 0;
}
XT7-1-2.CPP为简化主函数,可以将具体操作由专门函数实现
#include <iostream>
#include <cmath>
using namespace std;

void input(double a,double b,double c)
{cout<<"please input a,b,c:";
cin>>a>>b>>c;
}
void area(double a,double b,double c)
{double s,area;
if (a+b<=c)
cerr<<"a+b<=c,error!"<<endl;
else if(b+c<=a)
cerr<<"b+c<=a,error!"<<endl;
else if (c+a<=b)
cerr<<"c+a<=b,error!"<<endl;
else
{s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"area="<<area<<endl;}
}
int main()
{double a=2,b=3,c=5;
input(a,b,c);
area(a,b,c);
return 0;
}
XT7-2-1.CPP从键盘输入一批数值,要求保留三位小数,在输出时上下行小数点对齐,用控制符控制输出格式
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{float a[5];
cout<<"input data:";
for(int i=0;i<5;i++)
cin>>a[i];
cout<<setiosflags(ios::fixed)<<setprecision(2);
for(

i=0;i<5;i++)
cout<<setw(10)<<a[i]<<endl;
return 0;
}
XT7-2-2.CPP用流成员函数控制输出格式
#include <iostream>
using namespace std;
int main()
{float a[5];
int i;
cout<<"input data:";
for(i=0;i<5;i++)
cin>>a[i];
cout.setf(ios::fixed);
cout.precision(3);
for(i=0;i<5;i++)
{cout.width(10);
cout<<a[i]<<endl;}
return 0;
}
XT7-3.CPP编程序在显示屏上显示一个由字母B组成的三角形
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
for(int n=1;n<8;n++)
cout<<setw(20-n)<<setfill(' ')<<" " //nm
<<setw(2*n-1)<<setfill('B')<<"B"<<endl;
return 0;
}
XT7-4.CPP建立两个磁盘文件f1.dat和f2.dat,编程序实现一下工作
(1)从键盘输入20个整数,分别存放在两个磁盘文件中(每个
文件中放10个整数);
(2)从f1.dat中读入10个数,然后存放到f2.dat文件原有数据的后面
(3)从f2.dat中读入20个整数,将它们按从小到大的顺序存放到f2.dat不保留原有文件内容



#include <iostream>
#include <fstream>
using namespace std; //VC++ 6.0要此行
//fun1函数从键盘输入20个整数,分别存放在两个磁盘文件中

void fun1()
{int a[10];
ofstream outfile1("f1.dat"),outfile2("f2.dat"); //分别定义两个文件流对象
if(!outfile1) //检查打开f1.dat是否成功
{cerr<<"open f1.dat error!"<<endl;
exit(1);
}
if(!outfile2) //检查打开f2.dat是否成功
{cerr<<"open f2.dat error!"<<endl;
exit(1);
}
cout<<"enter 10 integer numbers:"<<endl;
for(int i=0;i<10;i++) //输入10个数存放到f1.dat文件中
{cin>>a[i];
outfile1<<a[i]<<" ";}
cout<<"enter 10 integer numbers:"<<endl;
for(i=0;i<10;i++) //输入10个数存放到f2.dat文件中
{cin>>a[i];
outfile2<<a[i]<<" ";}
outfile1.close(); //关闭f1.dat文件
outfile2.close(); //关闭f2.dat文件
}

//从f1,dat读入10个数,然后存放到f2.dat文件原有数据的后面
void fun2()
{ifstream infile("f1.dat"); //f1.dat作为输入文件
if(!infile)
{cerr<<"open f1.dat error!"<<endl;
exit(1);
}
ofstream outfile("f2.dat",ios::app);
//f2.dat作为输出文件,文件指针指向文件尾,向它写入的数据放在原来数据的后面
if(!outfile)
{cerr<<"open f2.dat error!"<<endl;
exit(1);
}
int a;
for(int i=0;i<10;i++)
{infile>>a; //磁盘文件f2.dat读入一个整数
outfile<<a<<" ";

//将该数存放到f2.dat中
}
infile.close();
outfile.close();
}

//从f2.dat中读入20个整数,将它们按从小到大的顺序存放到f2.dat
void fun3()
{ifstream infile("f2.dat"); //定义输入文件流infile,以输入方式打开f2.dat
if(!infile)
{cerr<<"open f2.dat error!"<<endl;
exit(1);
}
int a[20];
int i,j,t;
for(i=0;i<20;i++)
infile>>a[i]; //从磁盘文件f2.dat读入20个数放在数组a中
for(i=0;i<19;i++) //用起泡法对20个数排序
for(j=0;j<19-i;j++)
if(a[j]>a[j+1])
{t=a[j];a[j]=a[j+1];a[j+1]=t;}
infile.close(); //关闭输入文件f2.dat
ofstream outfile("f2.dat",ios::out);
// f2.dat作为输出文件,文件中原有内容删除
if(!outfile)
{cerr<<"open f2.dat error!"<<endl;
exit(1);}
cout<<"data in f2.dat:"<<endl;
for( i=0;i<20;i++)
{outfile<<a[i]<<" "; //向f2.dat输出已排序的20个数
cout<<a[i]<<" ";} //同时输出到显示器
cout<<endl;
outfile.close();
}

int main()
{fun1(); //分别调用3个函数
fun2();
fun3();
return 0;
}
XT7-5.CPP编程序实现一下功能。

1.
按职工号由小到大的顺序将5个员工的数据(包括号码、姓名、年龄、工资)输出到磁盘文件中保存

2. 从键盘输入两个员工的数据(职工号大于已有的职工号),增加到文件的末尾

3. 输出文件中全部职工的数据

4. 从键盘输入一个号码,从文件中查找有无此职工号,如有则显示从职工是第几个职工,以及此职工的全部数据。如没有,就输出“无此人”。可以反复多次查询,如果查找的职工号为0,就结束查询

#include <iostream>
#include <fstream>
using namespace std;
struct staff
{int num;
char name[20];
int age;
double pay;
};
int main()
{staff staf[7]={2101,"Li",34,1203,2104,"Wang",23,674.5,2108,"Fun",54,778,
3006,"Xue",45,476.5,5101,"Ling",39,656.6},staf1;
fstream iofile("staff.dat",ios::in|ios::out|ios::binary);
if(!iofile)
{cerr<<"open error!"<<endl;
abort();
}
int i,m,num;
cout<<"Five staff :"<<endl;
for(i=0;i<5;i++)
{cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
iofile.write((char *)&staf[i],sizeof(staf[i]));}
cout<<"please input data you want insert:"<<endl;
for(i=0;i<2;i++)
{cin>>staf1.num>>https://www.wendangku.net/doc/0816157158.html,>>staf1.age>>staf1.pay;
iofile.seekp(0,ios::end);
iofile.write((char *)&staf1,sizeof(staf1));}
iofile.seekg(0,ios::beg);
for(i=0;i<7;i++)
{iofile.read((char *)&am

p;staf[i],sizeof(staf[i]));
cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
}
bool find;
cout<<"enter number you want search,enter 0 to stop.";
cin>>num;
while(num)
{find=false;
iofile.seekg(0,ios::beg);
for(i=0;i<7;i++)
{iofile.read((char *)&staf[i],sizeof(staf[i]));
if(num==staf[i].num)
{m=iofile.tellg();
cout<<num<<" is No."<<m/sizeof(staf1)<<endl;
cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
find=true;
break;
}
}
if(!find)
cout<<"can't find "<<num<<endl;
cout<<"enter number you want search,enter 0 to stop.";
cin>>num;
}
iofile.close();
return 0;
}
c++工具
XT8-1.CPP求一元二次方程ax2+bx+c=0的实根,如果方程没有实根,则输出有关警告信息。
#include <iostream>
#include <cmath>
using namespace std;
double q(double,double,double);
void main()
{double a,b,c,p,x1,x2;
cout<<"please enter a,b,c:";
cin>>a>>b>>c;
p=-b/(2*a);
try
{x1=p+q(a,b,c);
x2=p-q(a,b,c);
cout<<"x1="<<x1<<endl<<"x2="<<x2<<endl;
}
catch(double d)
{cout<<"a="<<a<<",b="<<b<<",c="<<c<<",disc="<<d<<",error!"<<endl;}
cout<<"end"<<endl;
}

double q(double a,double b,double c)
{double disc;
disc=b*b-4*a*c;
if (disc<0) throw disc;
return sqrt(disc)/(2*a);
}
XT8-3.CPP学校的人事部门保存了有关学生的部分数据(学号、姓名、年龄、住址),教务部门也保存了学生的另外一些数据(学号、姓
名、性别、成绩),两个部门分别编写了本部门的学生数据管理程序,其中都用了Student作为类名。现在要求在全校的学生数据管理程序中调用这两个部门的学生数据,分别输出两种内容的学生数据。要求用ANSI C++编程,使用命名空间。
//main file
#include <iostream>
using namespace std;
#include "xt8-3-h1.h"
#include "xt8-3-h2.h"
using namespace std;
using namespace student1;

int main()
{Student stud1(1001,"Wang",18,"123 Beijing Road,Shanghua");
stud1.show_data();
student2::Student stud2(1102,"Li",'f',89.5);
stud2.show_data();
return 0;
}
XT8-3-H1.H
//header1.h,文件名为xt8-3-h1.h
#include <string>
namespace student1
{class Student
{public:
Student(int n,string nam,int a,string addr)
{num=n;name=nam;age=a;address=addr;}
void show_data();
private:
int num;
string name;
int age;
string address;


};
void Student::show_data()
{cout<<"num:"<<num<<" name:"<<name<<" age:"<<age
<<" address:"<<address<<endl;
}
}
XT8-3-H2.H
//header2.h,文件名为xt8-3-h2.h
#include <string>
namespace student2
{class Student
{public:
Student(int n,string nam,char s,float sco)
{num=n;name=nam;sex=s;score=sco;}
void show_data();
private:
int num;
string name;
char sex;
float score;
};

void Student::show_data()
{cout<<"num:"<<num<<" name:"<<name<<" sex:"<<sex
<<" score:"<<score<<endl; }
}

相关文档