您的当前位置:首页正文

C 面向对象程序设计源代码

2024-03-14 来源:步旅网
C++面向对象程序设计源代码.txt心是自己的,干嘛总被别人伤......没有伞的孩子必须努力奔跑▓敷衍旳青春 总昰想太多 怨,只怨现实太现实╰⌒﹏为什么在一起要两个人的同意丶而分手只需要一个人第 1 章 程序设计与C++概述 //e1_7.cpp

#include void main() {

int a,b,c;

cin>>a>>b; //输入两个整数 c = max(a,b);

cout<<\"max is\"<int max(int x,int y) {

int z;

z = (x>y?x:y); return z; }

//e1_8.cpp

#include void main() {

float r; //定义浮点型变量r,用于存放圆的半径 cout<<\"输入圆的半径:\";

cin>>r; //从键盘上输入圆的半径送给变量r

cout<<\"半径为\"<//e1_9.cpp

#include

float area(float r) //定义求半径为r的圆的面积的函数area { return 3.14159f * r * r; } void main() {

float r; //定义浮点型变量r,用于存放圆的半径 cout<<\"输入圆的半径:\"; //显示提示信息,提示用户输入数据 cin>>r; //从键盘上输入圆的半径送给变量r

cout<<\"半径为\"<//e1_10.cpp

#include

class Circle //定义一个计算圆的面积的类Circle {

private:

float r; //定义成员数据变量r,用于存放圆的半径

public:

Circle(float a) { r = a; } //定义构造函数,用于创建和初始化对象 ~Circle( ){} //定义析构函数,用于清理和撤销对象 void SetRadius(float a) { r = a; } //定义成员函数,用于设置圆的半径r float GetRadius(){ return r; } //定义成员函数,用于获取圆的半径r

float Area(){ return 3.14159f * r * r; }//定义成员函数Area,用于计算圆的面积 };

void main() {

float r; //定义浮点型变量r,用于存放圆的半径 cout<<\"输入圆的半径:\"; //显示提示信息,方便用户输入数据 cin>>r; //从键盘上输入圆的半径送给变量r Circle c(r); //定义Circle类的对象c

cout<<\"半径为\"<第2章 C++程序设计基础 //e2_1.cpp

#include const float PI = 3.1416 void main() {

float r,c,s; cin>>r;

c=2*PI*r; s=PI*r*r;

cout<<\"c=\"<//e2_2.cpp

#include void main() {

char c1,c2; int d1,d2;

cout<<\"请输入两个字符:\\n\"; cin>>c1>>c2;

d1=int(c1); //将c1强制转换为整型值赋给d1 d2=int(c2); //将c2强制转换为整型值赋给d2 cout<<\"输出整数对应的字符:\\n\";

cout<//e2_3.cpp

#include

void main() {

cout<<\"输出一个大数:\\"<<80000<cout<<\"输出一个分数:\\\"<<(float)5/8<cout<<\"输出一个特大数:\\"<<(double)8000*7000<第3章 程序流程控制 //e3_1.cpp

#include void main() {

int num1,num2,max;

cout<<\"input two numbers:\"; cin>>num1>>num2; max=num1;

if(max//e3_2.cpp

#include void main() {

int num1,num2;

cout<<\"input two numbers:\" ; cin>>num1>>num2; if(num1>num2)

cout<<\"max=\"<cout<<\"max=\"<//e3_3.cpp

#include void main() {

float score;

cout<>score; if(score>=85)

cout<<\"the score \"<=75)

cout<<\"the score \"<=60)

cout<<\"the score \"<cout<<\"the score \"<//e3_4.cpp

#include void main() {

int num;

cin>>num; switch(num) {

case 1:cout<<\"Monday\\n\";break; case 2:cout<<\"Tuesday\\n\";break; case 3:cout<<\"Wednesday\\n\";break; case 4:cout<<\"Tursday\\n\";break; case 5:cout<<\"Friday\\n\";break; case 6:cout<<\"Saturday\\n\";break; case 7:cout<<\"Sunday\\n\";break; default:cout<<\"error\\n\"; } }

//e3_5.cpp

#include void main() {

int sum=0,i; i=1;

while(i<=100) {

sum=sum+i; i++; }

cout<<\"sum=\"<//e3_6.cpp

#include void main() {

int m,n;

for(m=1;m<=9;m++) {

for(n=1;n<=9;n++)

cout<}

//e3_7.cpp

#include void main() {

int m,n;

cout<<\"please input the number m:\\n\"; cin>>m;

for(n=2;n<=m/2;n++) if(m%n==0) break; if(n>m/2)

cout<cout<//e3_8.cpp

#include void main() {

int m,n;

cout<<\"the prime number is:\\n\"; for(m=3;m<100;m+=2) {

for(n=2;n<=m/2;n++) if(m%n==0) break; if(n//e3_9cpp

#include void main() {

int x,y,z,t;

cout<<\"please input 3 numbers:\"; cin>>x>>y>>z; if (x>y)

{t=x;x=y;y=t;} //交换x,y的值 if(x>z)

{t=z;z=x;x=t;} //交换x,z的值 if(y>z)

{t=y;y=z;z=t;} //交换z,y的值 cout<//e3_10.cpp

#include void main() {

int day,month,year,sum,leap;

cout<<\"please input year,month,day\\n\"; cin>>year>>month>>day;

switch(month) //先计算某月以前月份的总天数 {

case 1:sum=0;break; case 2:sum=31;break; case 3:sum=59;break; case 4:sum=90;break; case 5:sum=120;break; case 6:sum=151;break; case 7:sum=181;break; case 8:sum=212;break; case 9:sum=243;break; case 10:sum=273;break; case 11:sum=304;break; case 12:sum=334;break;

default: cout<<\"data error\";break; }

sum=sum+day; //再加上某天的天数 if(year%400==0||(year%4==0&&year%100!=0)) //判断是不是闰年 leap=1; else leap=0;

if(leap==1&&month>2) //如果是闰年且月份大于2,总天数应该加一天 sum++;

cout<<\"It is the \"<//e3_11.cpp

#include void main() {

int a,b,m,n,t,r;

cout<<\"please input 2 numbers:\\n\"; cin>>m>>n; if(m{t=m;m=n;n=t;} //将m,n中大值赋给m a=m; b=n;

while(b!=0) //利用辗除法,直到b为0为止 {

r=a%b; a=b; b=r; }

cout<<\"greatest common divisor:\"<//e3_12.cpp

#include void main() {

int i,j,k;

for(i=1;i<=4;i++) {

for(j=1;j<=2*i-1;j++) cout<<\"*\";

for(k=1;k<=6-2*i;k++) cout<<\" \"; cout<for(i=1;i<=3;i++) {

for(j=1;j<=7-2*i;j++) cout<<\"*\"; for(k=1;k<=2*i;k++) cout<<\" \"; cout<第4章 数组 //e4_1.cpp

#include

#include //使用控制符setw,要包含头文件iomanip.h void main() {

int i,a[7];

cout<<\"please input 7 numbers:\\n\"; for(i=0;i<=6;i++) cin>>a[i]; for(i=0;i<=6;i++)

cout<//e4_2.cpp

#include void main()

{ int x[10],i,j;

j=0; //计数器初值赋0 cout<<\"please input 10 numbers:\"<for(i=0;i<=9;i++) //顺序的输入数组x的10个元素

cin>>x[i];

for(i=0;i<=9;i++) //逐个的比较数组的各个元素和0的大小 if(x[i]>0) j++; cout<<\"j=\"<#include void main() {

int a[11];

int i,n,t; //i表示数组下标,n表示遍历次数,t用来交换数据 cout<<\"input 10 numbers:\"<>a[i];

cout<for(n=1;n<=9;n++)

for(i=1;i<=10-n;i++) if(a[i]>a[i+1])

{t=a[i];a[i]=a[i+1];a[i+1]=t;} cout<<\"the sorted numbers:\"<//e4_4.cpp

#include void main() {

int a[2][3]={{1,5,9},{2,6,8}}; int b[3][2],i,j;

cout<<\"Array a: \"<for(j=0;j<3;j++) {

cout<b[j][i]=a[i][j]; //将两个数组元素相互交换 }

cout<cout<<\"Array b:\"<for(j=0;j<2;j++)

cout<//e4_5.cpp

#include void main() {

float score[6][3],sv[6],x; int i,j;

cout<<\"input the 6 student's score:\"<>x;

score[i][j]=x; //输入每个学生的每门课成绩 }

for(i=0;i<6;i++) { sv[i]=0;

for(j=0;j<3;j++) //求每个学生的总成绩 sv[i]=sv[i]+score[i][j];

sv[i]=sv[i]/3; //求每个学生的平均成绩 }

for(i=0;i<6;i++) //输出每个学生的平均成绩 cout<<\"Student \"<//e4_7.cpp

#include #include void main() {

char str[20]; int i,j;

cout<<\"please input a string:\"; cin.get(str,20); j=strlen(str); for(i=j-1;i>=0;i--) cout.put(str[i]); }

//e4_8.cpp

#include #include void main()

{

char str1[20],str2[20],str3[50]; cin.getline(str1,20); cin.getline(str2,20); if (strcmp(str1,str2)<0) {

strcpy(str3,str1); strcat(str3,str2); } else {

strcpy(str3,str2); strcat(str3,str1); }

cout<//e4_9.cpp

#include void main() {

float a[3][3],sum=0,x; int i,j;

cout<<\"input 3*3 Matrix:\"<cin>>x; a[i][j]=x; }

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

sum=sum+a[i][i]+a[i][2-i]; cout<<\"the sum is:\"<//e4_10.cpp

#include #include void main() {

char str[60]; int i,j;

cin.get(str,60); i=0;

j=strlen(str)-1;

while(str[i]=='') i++; //寻找前面第一个不是空格的字符

while(str[j]=='') j--; //寻找后面第一个不是空格的字符 while(icout<<\"No\"<cout<<\"Yes\"<//e4_11.cpp

#include void main() {

int i,j,a[10],t,k;

cout<<\"input 10 numbers: \"<for(i=0;i<10;i++) //输入10个要排序的数据 cin>>a[i];

for(i=0;i<9;i++) //排序总共进行了9趟 {

k=i; //初始化最小数的下标

for(j=i+1;j<10;j++) //从当前数的后面寻找最小数的下标 if(a[j]k=j; //记录新的最小数的下标 if(k!=i)

{ t=a[i];a[i]=a[k];a[k]=t;} //第i个数和最小数交换 }

for(i=0;i<10;i++) //输入排序后的10个数 cout<第5章 模块设计 //程序1 //e5_1.cpp

#include void main() {

int x,y,z; cin>>x>>y; z=x+y;

cout<<\"\\n The sum is\"<//程序2

#include

int sum(int a,int b) //被调用函数sum的定义 {

int s;

s=a+b; return s; }

void main() {

int x,y,z;

int sum(int,int); //函数声明 cin>>x>>y;

z=sum(x,y); //函数调用 cout<//e5_2.cpp

#include

void swap(int x,int y); //函数声明 void main() {

int a=50,b=60;

cout<<\"a=\"<swap(a,b); //调用函数 cout<<\"a=\"<void swap(int x,int y) //定义函数 {

int z; z=x;x=y;y=z; }

//e5_3.cpp

#include

int add(int x, int n) //定义函数 {

return(x+n); }

void main() {

int add(int x, int n); //函数声明 int i;

int a[10]={9,8,7,6,5,4,3,2,1,0}; for(i=0;i<10;i++)

a[i]=add(a[i],i); //数组元素作函数参数 for(i=0;i<10;i++) cout<//e5_4.cpp

#include

void swap(int *x,int *y); //函数声明,形参x和y为指针变量 void main() {

int a=50,b=60;

cout<<\"a=\"<swap(&a,&b); //调用函数,实参为变量a和b的地址 cout<<\"a=\"<void swap(int *x,int *y) //定义函数 {

int z;

z=*x;*x=*y;*y=z; }

//e5_5.cpp

#include

float average(float array[10]); //函数声明 void main() {

float score[10],aver; int i;

cout<<\"input 10 scores:\"<>score[i]; cout<aver=average(score); //函数调用,一维数组名score作为参数 cout<<\"average score is \"<float average(float array[10]) //函数定义 {

int i;

float aver,sum=0.0; for(i=0;i<10;i++) sum=sum+array[i]; aver=sum/10; return(aver); }

//e5_6.cpp

#include

int max_element(int array[4][4]); //函数声明 void main() {

int p[4][4]={{1,22,3,4},{3,4,6,18},{6,5,2,9},{0,6,1,34}};

cout<<\"max is :\"<int max_element(int array[4][4]) //函数定义 {

int i,j,max; max=array[0][0]; for(i=0;i<4;i++) for(j=0;j<4;j++)

if(array[i][j]>max) max=array[i][j]; return(max); }

//e5_7.cpp

#include

void print(int p[]); //函数声明 void main() {

int score[3][4]={{87,81,65,74},{93,84,72,88},{76,85,92,99}}; int num;

cout<<\"input NO(0 - 2):\"; cin>>num;

print(score[num]); //函数调用,二维数组列地址作为参数 }

void print(int p[]) //函数定义 {

int i;

for(i=0;i<4;i++) cout<//e5_8.cpp

#include void main() {

int i=2,j=3,k; k=i+j; {

int k=14;

if(i==2) cout<cout<//e5_9.cpp

#include int s1,s2,s3;

int vs( int a,int b,int c) {

int v;

v=a*b*c; s1=a*b; s2=b*c; s3=a*c; return v; }

void main() {

int v,l,w,h;

cout<<\"input length,width and height:\"; cin>>l>>w>>h; v=vs(l,w,h);

cout<<\"v=\"<//e5_10.cpp

#include

int fun(int x,int y,int z) //函数定义 {

int v; v=x*y*z; return v; }

void main() {

extern int w,h; //外部变量说明,以扩展变量w、h的作用范围 int l=5;

cout<<\"v=\"<int l=3,w=4,h=5; //外部变量定义 //e5_11.cpp

#include void main() {

auto int a,s=10,p=10; cout<<\"input a number:\"; cin>>a; if(a>0) {

auto int s,p; s=a+a; p=a*a;

cout<<\"s=\"<cout<<\"s=\"<}

//e5_12.cpp

#include void main() {

int i;

void f(); //函数声明 for(i=1;i<=4;i++)

f(); //函数调用 }

void f() //函数定义 {

auto int j=0; ++j;

cout<//e5_14.cpp

#include

float sum(float x,float y,float z); float average(float a,float b,float c); void main() {

float num1,num2,num3;

cout<<\"Input the scores of the three courses:\"; cin>>num1>>num2>>num3;

cout<<\"The total score is:\"<cout<<\"The average score is:\"<float sum(float x,float y,float z) {

float m=x+y+z; return m; }

float average(float a,float b,float c) {

float n=(sum(a,b,c))/3; return n; }

//e5_15.cpp

#include long fac(int n) {

long t;

if((n==1)||(n==0))

return 1; else

t=n*fac(n-1); return t; }

void main() {

long fac(int n); int m; long y;

cout<<\"Enter m:\"; cin>>m; if(m<0)

cout<<\"Input data Error!\"<y=fac(m);

cout<//e5_16.cpp

#include

#include //使用控制符setw,要包含头文件iomanip.h #define MAX 100

int fun( int m, int prime[MAX]) {

int i,j=0,k;

for( k=2;kfor(i=2;iif(i>=k) prime[j++]=k; }

return j; }

void main() {

int m,i,sum; int prime[MAX];

cout<<\"input a integer number:\"; cin>>m;

sum=fun(m,prime);

cout<<\"The prime number is:\"<if(i%5==0&&i!=0)

cout<cout<//e5_17.cpp

#include #include

void f(char s[],char t[]) {

int i,s1; s1=strlen(s);

for(i=0;i<=s1;i++) t[i]=s[i]; for(i=0;it[s1+i]=s[s1-i-1]; t[s1+s1]='\\0'; }

void main() {

char s[100],t[100];

cout<<\"Please enter string s:\"; cin.get(s,100); f(s,t);

cout<<\"The result is:\"<//e5_18.cpp

#include int max(int x,int y) {

int z;

z = (x>y?x:y); return z; }

float max(float x,float y) {

float z;

z = (x>y?x:y); return z; }

void main() {

int num1,num2; float num3,num4;

cin>>num1>>num2>>num3>>num4;

cout<<\"max(num1,num2)=\"<//e5_19.cpp

#include void main() {

int max(int a,int b,int c=0); int a,b,c; cin>>a>>b>>c;

cout<<\"max(a,b,c)= \"<int max(int a,int b,int c) {

if (b>a) a=b; if (c>a) a=c; return a; }

//e5_20.cpp

#include template T max(T x,T y) {

return x>y?x:y; }

void main() {

int num1,num2; float num3,num4;

cin>>num1>>num2>>num3>>num4;

cout<<\"max(num1,num2)=\"<//e5_21.cpp

#include

template T2 max(T1 x,T2 y) {

return x>y?x:y; }

void main() {

int num1,num2;

float num3,num4;

cin>>num1>>num2>>num3>>num4;

cout<<\"max(num1,num2)=\"<cout<<\"max(num3,num4)=\"<//e5_22.cpp

#include #define R 1 void main() {

double c,r,s;

cout<<\"input a number: \"; cin>>c; #if R

r=3.14159*c*c;

cout<<\"area of round is: \"<s=c*c;

cout<<\"area of square is: \"<//e5_23.cpp

#include

#define S(a,b) ((a>b)?(a):(b)) //定义带参数的宏名S void main() {

int x,y; cin>>x>>y;

cout<y)?(x):(y)) }

第6章 指针 //e6_1.cpp

#include void main() {

int *p1,*p2,*p,a,b; cin>>a>>b; p1=&a;p2=&b; if(a{p=p1;p1=p2;p2=p;}

cout<<\"a=\"<cout<<\"max=\"<<*p1<<\"\min=\"<<*p2<}

//e6_2.cpp

#include void main() {

int **p1,*p2,n; n=3; p1=&p2; p2=&n;

cout<<**p1; }

//e6_3.cpp

#include swap(int *p1,int *p2) {

int *p; p=p1; p1=p2; p2=p; }

void main() {

int a,b;

int *pointer_1,*pointer_2; cout<<\"input a,b: \"; cin>>a>>b;

pointer_1=&a;pointer_2=&b;

if(a//e6_5.cpp

#include void main() {

int *p,i,a[10]; p=a;

for(i=0;i<10;i++) *p++=i;

for(i=0;i<10;i++) cout<<*p++<<'\'; }

//e6_6.cpp

#include

int sub_max(int b[],int n)

{

int temp,i; temp=b[0];

for(i=1;iif(tempvoid main() {

int i,a[10],*pt=a,max;

cout<<\"please input array a:\\n\"; for(i=0;i<10;i++) cin>>a[i];

max=sub_max(pt,10); cout<//e6_9.cpp

#include void main() {

int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11}; int (*p)[4]; int i,j; p=a;

for(i=0;i<3;i++) {

for(j=0;j<4;j++)

cout<<*(*(p+i)+j)<< '\'; cout<//e6_15.cpp

#include void main() {

int a[3][3]={1,2,3,4,5,6,7,8,9}; int * pa[3]; int * p=a[0]; int i;

pa[0]=a[0];pa[1]=a[1];pa[2]=a[2]; for(i=0;i<3;i++)

cout<cout<<*pa[i]<//e6_16.cpp

#include #include void main() {

void sort(char *name[],int n); void print(char *name[],int n);

char *name[]={\"CHINA\ int n=5;

sort(name,n); print(name,n); }

void sort(char *name[],int n) {

char *pt; int i,j,k;

for(i=0;ik=i;

for(j=i+1;jif(strcmp(name[k],name[j])>0) k=j; if(k!=i) {

pt=name[i];

name[i]=name[k]; name[k]=pt; } } }

void print(char *name[],int n) {

int i;

for(i=0;i#include void main() {

int i;

char *day_name(int n); cout<<\"input Day No:\\n\"; cin>>i;

if(i<0) {cout<<\"Error!\\n\";return 0;}

cout<<\"Day No:\"<\"<char *day_name(int n) {

static char *name[]={ \"Illegal day\ \"Monday\ \"Tuesday\ \"Wednesday\ \"Thursday\ \"Friday\ \"Saturday\ \"Sunday\ return((n<1||n>7)?name[0]:name[n]); }

//e6_19.cpp

#include int max(int a,int b) {

if(a>b) return a; else return b; }

void main() {

int max(int a,int b); int (*pmax)(int ,int); int x,y,z; pmax=max;

cout<<\"input two numbers:\\n\"; cin>>x>>y; z=pmax(x,y);

cout<<\"maxmum= \"<//e6_20.cpp

#include void main() {

int num = 500; int & ref = num; ref = ref + 100;

cout<<\"num=\"<//e6_21.cpp

#include void swap(int x,int y) {

int t; t = x; x = y; y = t; }

void main() {

int a = 1,b = 2;

cout<<\"交换前,a=\"<cout<<\"交换后,a=\"<//e6_22.cpp

#include

void swap(int * x,int * y) {

int t; t = *x; *x = *y; *y = t; }

void main() {

int a = 1,b = 2;

cout<<\"交换前,a=\"<cout<<\"交换后,a=\"<//e6_23.cpp

#include

void swap(int & x,int & y) {

int t; t = x; x = y; y = t; }

void main() {

int a = 1,b = 2;

cout<<\"交换前,a=\"<swap(a,b);

cout<<\"交换后,a=\"<//e6_24.cpp

#include

int & min(int & i,int & j)//此函数的返回值是对参数i和j中小的那个变量的引用 {

if(i<=j) return i; else

return j; }

void main() {

int a = 3, b= 4;

cout<<\"a=\"<min(a,b)=5; //由于函数的返回值为引用类型,所以可以为函数赋值 //为函数赋的值赋给两个参数中的小者,所以a变为5,b仍为4 cout<<\"a=\"<min(a,b) = 0; //a不变,b变为0 cout<<\"a=\"<//e6_25.cpp

#include

void prime(int n,int *f) {

int k;

*f=1;

for(k=2;k<=n/2;k++) if(!(n%k)) *f=0; }

void main() {

int m,m1,flag1,flag2; for(m=10;m<100;m++) {

m1=(m%10)*10+m/10; prime(m,&flag1); prime(m1,&flag2);

if (flag1&&flag2) cout<//e6_26.cpp

//用数组作为函数参数

#include

void inverse(int a[],int m,int n) {

int i,j,t;

for(i=m-1,j=m+n-2;i<=m-1+n/2;i++,j--) {

t=a[i];a[i]=a[j];a[j]=t; } }

void main() {

int i,a[10]={1,2,3,4,5,6,7,8,9,10}; inverse(a,2,7); for(i=0;i<10;i++) cout<//用指针变量作为函数参数

主函数不变,函数inverse()改写为: void inverse(int *p,int m,int n) {

int *p1,*p2,t;

for(p1=p+m-1,p2=p+m+n-2;p1<=p+m-1+n/2;p1++,p2--) {

t=*p1;*p1=*p2;*p2=t; } }

//e6_27.cpp

#include void main() {

void del_ch(char *,char); char str[80],*pt,ch;

cout<<\"Input a string:\\n\"; cin.get(str,80); pt=str;

cout<<\"Input the char deleted:\\n\"; cin>>ch;

del_ch(pt,ch);

cout<<\"Then new string is:\"<void del_ch(char * p,char ch) {

int i;

char *q;

for(q=p;*p!='\\0';p++)

if(*p!=ch) *q++=*p; *q='\\0'; }

//e6_28.cpp

#include #include void main() {

char * ptr1[4],str[4][20],temp[20]; int i,j;

for(i=0;i<4;i++) cin>>str[i]; cout<for(i=0;i<4;i++) ptr1[i]=str[i];

cout<<\"Original string:\\n\"; for(i=0;i<4;i++) cout<if(strcmp(ptr1[j],ptr1[j+1])>0) {

strcpy(temp,ptr1[j]);

strcpy(ptr1[j],ptr1[j+1]); strcpy(ptr1[j+1],temp); }

cout<<\"Sorted string:\\n\"; for(i=0;i<4;i++) cout<第7章 类和对象 //e7_1.cpp

#include

class Date {

public:

void SetDate(int y, int m, int d) // {

year = y; month = m; day = d;

//定义日期类 设置日期成员函数 }

int IsLeapYear() //判定是否闰年成员函数 {

return(year%4==0 && year%100!=0)||(year%400==0); }

void Print() //输出日期成员函数 {

cout<int year, month, day; //数据成员 };

void main() {

Date today; //定义日期对象 today.SetDate(2007,12,31); today.Print(); } //7.2

//Triangle.h

#include

class Triangle //定义三角形类 {

public:

void SetTriangle(int x, int y, int z); //设置三角形成员函数 double GetArea(); //求三角形面积 int GetPerimeter(); //求三角形周长 void Print(); //输出三角形信息 private:

int a,b,c; //数据成员 };

//返回面积较大的三角形

Triangle & compare(Triangle & t1, Triangle & t2); //Triangle.cpp #include #include \"Triangle.h\"

void Triangle::SetTriangle(int x, int y, int z) //设置三角形成员函数 {

a = x; b = y; c = z; }

double Triangle::GetArea() //求三角形面积 {

double s;

s = (a + b + c)/2.0;

return sqrt( s*(s-a)*(s-b)*(s-c)); }

int Triangle::GetPerimeter() //求三角形周长 {

return (a + b + c); }

void Triangle::Print() //输出三角形信息 {

cout<<\"the three side of the triangle is:\"<Triangle & compare(Triangle & t1, Triangle & t2) {

if(t1.GetArea()>t2.GetArea()) return t1; else

return t2; }

//e7_2.cpp

#include \"Triangle.h\" void main() {

Triangle t1; //定义三角形对象 t1.SetTriangle(4,5,6);

Triangle t2; //定义三角形对象 t2.SetTriangle(7,8,9);

Triangle & max = compare(t1,t2); max.Print(); }

//e7_3.cpp

#include

class Date //定义日期类 {

public:

Date() //不带参数的构造函数 {

year = 2007; month = 12; day = 31; }

Date(int y, int m, int d) //带参数的构造函数

{

year = y; month = m; day = d; }

void SetDate(int y, int m, int d) //设置日期成员函数 {

year = y; month = m; day = d; }

int IsLeapYear() //判定是否闰年成员函数 {

return(year%4==0 && year%100!=0)||(year%400==0); }

void Print() //输出日期成员函数 {

cout<int year, month, day; //数据成员 };

void main() {

Date today; //定义日期对象 Date tomorrow(2008,1,1); //定义日期对象 today.Print(); tomorrow.Print(); } //7-4

//Complex.h

class Complex //复数类 {

private:

double re; //实部 double im; //虚部 public:

Complex(); //第1个构造函数 Complex(double r); //第2个构造函数 Complex(double r, double i); //第3个构造函数 void Display(); };

//Complex.cpp

#include

#include \"Complex.h\" Complex::Complex() {

re = 0; im = 0; }

Complex::Complex(double r) {

re = r; im = 0; }

Complex::Complex(double r, double i) {

re = r; im = i; }

void Complex::Display() {

cout<//e7_4.cpp

#include \"Complex.h\" void main() {

Complex c1; //定义复数对象,调用Complex()

Complex c2(3); //定义复数对象,调用Complex(double r)

Complex c3(5, 6); //定义复数对象,调用Complex(double r, double i) c1.Display(); c2.Display(); c3.Display(); } //7-5 //Array.h

#include class Array {

int * a; //指向动态数组的指针 int n; //数组大小 public:

Array(int aa[],int nn); //构造函数 ~Array(); //析构函数 int Lenth() //取数组大小 {

return n;

}

void Print() //输出数组 {

for(int i=0; i//Array.cpp

#include \"Array.h\"

Array::~Array() //析构函数 {

delete[] a; }

Array::Array(int aa[],int nn)//构造函数 {

n = nn;

a = new int[n];

for(int i=0; i//e7_5.cpp

#include #include \"Array.h\" void main() {

int aa[6] = {1,2,3,4,5,6}; Array a1(aa,6); Array b1(a1);

cout<//e7_6.cpp

#include class Test {

private: int num; public:

Test(int a) {

num = a;

cout<<\"第\"<~Test() {

cout<<\"第\"<void main() {

cout<<\"进入main函数\"<Test t[4] = {0,1,2,3}; //定义4个对象,分别以0,1,2,3赋给构造函数的形参a cout<<\"main函数在运行中\"<//Complex.h

class Complex //复数类 {

private:

double re; //实部 double im; //虚部 public:

Complex(); //第1个构造函数 Complex(double r); //第2个构造函数 Complex(double r, double i); //第3个构造函数 void Display(); };

//Complex.cpp

#include #include \"Complex.h\" Complex::Complex() {

re = 0; im = 0; }

Complex::Complex(double r) {

re = r; im = 0; }

Complex::Complex(double r, double i) {

re = r; im = i;

}

void Complex::Display() {

cout<//e7_7.cpp

#include \"Complex.h\" void main() {

Complex * pc1 = new Complex; //定义复数对象,调用Complex()

Complex * pc2 = new Complex(3); //定义复数对象,调用Complex(double r)

Complex * pc3 = new Complex(5, 6); //定义复数对象,调用Complex(double r, double i)

pc1->Display(); //(*pc1).Display(); pc2->Display(); //(*pc2).Display(); pc3->Display(); //(*pc3).Display(); delete pc1; delete pc2; delete pc3; } //7-8

//Student.h

class Student //学生类 {

public:

Student(); //构造函数 Student(char *,char *,int); //构造函数 ~Student(); //析构函数 private:

char name[20]; //姓名 char id[20]; //学号 int score; //成绩 public:

static int total; //学生对象计数--静态数据成员 };

//Student.cpp

#include #include \"Student.h\"

Student::Student() //构造函数 {

strcpy(name,\"noname\"); strcpy(id,\"0000000\"); score = 0;

total++; //构造函数被调用,表明有学生对象创建

}

Student::Student(char * name,char * id,int score) //构造函数 {

strcpy(this->name,name); strcpy(this->id,id); this->score=score;

total++; //构造函数被调用,表明有学生对象创建 }

Student::~Student() {

total--; //析构函数被调用,表明有学生对象减少 }

//e7_8.cpp

#include #include \"Student.h\"

int Student::total = 0; //静态数据成员的初始化 void main() {

Student a(\"Wang Tao\创建局部对象a,total值应为1 Student b(\"Yang Ling\创建局部对象b,total值应为2 Student c(\"Liu XiaoLu\创建局部对象c,total值应为3 cout<<\"number of student: \"<Student * pe = new Student(\"Liang Wei\创建堆对象,total值应为5

cout<<\"number of student: \"<cout<<\"number of student: \"<cout<<\"number of student: \"<//7-10

//Customer.h

class Customer //客户类 {

friend class BankQueue; //将BankQueue类声明为Customer类的友元类 private:

int account; //账号

int amount; //金额,大于0表示存款,小于0表示取款 public:

Customer(int account = -1,int amount = 0);//默认参数的构造函数 int GetAccount(); //取账号 int GetAmount(); //取金额

};

//BankQueue.h

#include \"Customer.h\"

const int ARRAY_SIZE = 10;

class BankQueue //队列类 {

public:

BankQueue(); //构造函数 void EnQueue(Customer newElem); //元素入队列 Customer DelQueue(); //元素出队列 int GetLength() //取队列长度 {

return length; }

void Print() const; //常量成员函数,输出队列 private:

Customer elem[ARRAY_SIZE]; //存放队列元素的数组 int first; //队列首元素位置 int length; //队列长度 };

//Customer.cpp

#include \"Customer.h\"

Customer::Customer(int account,int amount) //构造函数 {

this->account = account; this->amount = amount; }

int Customer::GetAccount() //取账号 {

return account; }

int Customer::GetAmount() //取金额 {

return amount; }

//BankQueue.cpp

#include #include \"BankQueue.h\"

BankQueue::BankQueue() //构造函数 {

first = length = 0; }

void BankQueue::EnQueue(Customer newElem)//元素入队列 {

int pos = (first+length)%ARRAY_SIZE; //计算新元素的存放位置 elem[pos] = newElem; //存储新元素 length++; //队列长度加1 }

Customer BankQueue ::DelQueue() //元素出队列 {

//暂存队列首元素,访问了Customer类的私有数据成员 Customer ret(elem[first].account,elem[first].amount); first = (first+1)%ARRAY_SIZE; //队列首元素位置进1 length--; //队列长度减1 return ret; //返回队列首元素 }

void BankQueue::Print() const //常量成员函数,输出队列 {

int pos = first;

cout<<\"队列中客户: \"<//访问了Customer类的私有数据成员

cout<<\"账号: \"<cout<//e7_10.cpp

#include #include \"BankQueue.h\" void main() {

BankQueue q; int i;

for(i=0; i<6; i++)

q.EnQueue(Customer(i+1,100*(i+1))); q.Print(); Customer a;

for(i=0; i<3; i++) {

a = q.DelQueue();

cout<<\"出队列: \"<cout<//e7_11.cpp

#include #include

class Salary //定义工资类 {

public:

float m_fWage; //基本工资 float m_fSubsidy; //岗位津贴 float m_fRent; //房租 float m_fCostOfElec; //电费 float m_fCostOfWater; //水费 public:

float RealSum() //计算实发工资 {

return m_fWage+m_fSubsidy-m_fRent-m_fCostOfElec-m_fCostOfWater; } };

enum Position //定义职务类型 {

MANAGER, //经理 ENGINEER, //工程师 EMPLOYEE, //职员 WORKER //工人 };

class Date //定义日期类 {

int day,month,year; public:

void init(int,int,int); void print_ymd(); };

class Employee //定义职工类 {

char m_sDepartment[20]; //工作部门 char m_sName[10]; //姓名 Date m_tBirthdate; //出生日期 Position m_nPosition; //职务

Date m_tDateOfWork; //参加工作时间 Salary m_fSalary; //工资 public:

void Register(char *Depart, char *Name,Date tBirthdate,Position nPosition,Date tDateOfWork);

void SetSalary(float wage ,float subsidy,float rent ,float elec,float water); float GetSalary();

void ShowMessage(); //打印职工信息

};

void Date::init(int yy,int mm,int dd) {

month = (mm>=1 && mm<=12)?mm:1;

year = (yy>=1900 && yy<=2100)?yy:1900; day = (dd>=1 && dd<=31)?dd:1; }

void Date::print_ymd() {

cout<void Employee::Register(char *Depart,char *Name,Date tBirthdate,Position nPosition,Date tDateOfWork) {

strcpy(m_sDepartment,Depart); strcpy(m_sName,Name);

m_tBirthdate = tBirthdate; m_nPosition = nPosition; m_tDateOfWork = tDateOfWork; }

void Employee::SetSalary(float wage,float subsidy,float rent ,float elec,float water) {

m_fSalary.m_fWage = wage;

m_fSalary.m_fSubsidy = subsidy; m_fSalary.m_fRent = rent;

m_fSalary.m_fCostOfElec = elec; m_fSalary.m_fCostOfWater = water; }

float Employee::GetSalary() {

return m_fSalary.RealSum(); }

void Employee::ShowMessage() {

cout<<\"Depart:\"<m_tBirthdate.print_ymd(); switch(m_nPosition) {

case MANAGER:

cout<<\"Position:\"<<\"MANAGER\"<case ENGINEER:

cout<<\"Position\"<<\"ENGINEER\"<case EMPLOYEE:

cout<<\"Position\"<<\"EMPLOYEE\"<cout<<\"Position\"<<\"WORKER\"<cout<<\"Date of Work:\"; m_tDateOfWork.print_ymd();

cout<<\"Salary:\"<#define MAX_EMPLOYEE 1000 void main() {

Employee EmployeeList[MAX_EMPLOYEE];//定义职工档案数组 int EmpCount = 0;

Date birthdate, workdate; //输入第一个职工数据 birthdate.init(1980,5,3); workdate.init(1999,7,20);

EmployeeList[EmpCount].Register(\"工程部\张三\EmployeeList[EmpCount].SetSalary(1000,200,100,50,20); EmpCount++;

//输入第二个职工数据

birthdate.init(1979,4,8); workdate.init(2002,3,1);

EmployeeList[EmpCount].Register(\"售后服务部\李四\EmployeeList[EmpCount].SetSalary(1500,200,150,50,20); EmpCount++;

//输出所有职工的记录

for(int i=0; i第8章 继承与派生 //e8_1.cpp

#include #include

class Person //人员类定义 {

protected:

char m_strName[10]; //姓名 int m_nAge; //年龄 int m_nSex; //性别 public:

void Register(char * name,int age,char sex) {

strcpy(m_strName,name); m_nAge = age;

m_nSex = (sex=='m'?0:1); }

char * GetName() //取姓名 {

return m_strName; }

int GetAge() //取年龄 {

return m_nAge; }

char GetSex() //取性别 {

return m_nSex==0?'m':'f'; }

void ShowMe() {

cout<class Employee:public Person //雇员类定义 {

char m_strDept[20]; //工作部门 float m_fSalary; //月薪 public: Employee() {

EmployeeRegister(\"XXX\}

void EmployeeRegister(char * name,int age,char sex,char * dept,float salary); void ShowMe(); };

void Employee::EmployeeRegister(char * name,int age,char sex,char * dept,float salary) {

Register(name,age,sex);

strcpy(m_strDept,dept); m_fSalary=salary; }

void Employee::ShowMe() {

//子类的成员函数可以调用基类的公有成员函数

cout<cout<void main() {

Employee emp; emp.ShowMe();

emp.EmployeeRegister(\"张莉\图书馆\emp.ShowMe();

//基类的ShowMe()在公有继承方式下相当于派生类的公有成员,在main()中可以显式访问基类成员

emp.Person::ShowMe();

cout<<\"调用基类 GetName() 返回值为:\"<//e8_2.cpp

#include #include class Person {

protected:

char m_strName[10]; int m_nAge; int m_nSex; public:

void Register(char * name,int age,char sex) {

strcpy(m_strName,name); m_nAge = age;

m_nSex = (sex=='m'?0:1); }

char * GetName() {

return m_strName; }

int GetAge() {

return m_nAge;

}

char GetSex() {

return m_nSex==0?'m':'f'; }

void ShowMe() {

cout<class Employee:private Person {

char m_strDept[20]; float m_fSalary; public:

Employee() {

EmployeeRegister(\"XXX\}

void EmployeeRegister(char * name,int age,char sex,char * dept,float salary); void ShowMe();

char * GetEmployeeName(){return GetName();} char GetEmployeeSex(){return GetSex();} int GetEmployeeAge(){return GetAge();} };

void Employee::EmployeeRegister(char * name,int age,char sex,char * dept,float salary) {

Register(name,age,sex); strcpy(m_strDept,dept); m_fSalary=salary; }

void Employee::ShowMe() {

cout<cout<//基类的保护类成员相当于派生类的私有成员,子类的成员函数可以直接访问 cout<void main() {

Employee emp;

emp.EmployeeRegister(\"张三\图书馆\emp.ShowMe();

//基类的ShowMe函数在私有继承方式下相当于派生类的私有成员,在main函数中不可以访问,即在main函数中不能使用显式访问基类成员emp.Person::ShowMe();

cout<<\"调用基类 GetName() 返回值为:\"<//e8_3.cpp

#include

class Point //定义基类,表示点 {

private: int x; int y; public:

void setPoint(int a, int b){ x=a; y=b; }; //设置坐标 int getX(){ return x; }; //取得X坐标 int getY(){ return y; }; //取得Y坐标 };

class Circle:public Point //定义派生类,表示圆 {

private:

int radius; public:

void setRadius(int r){ radius=r; }; //设置半径 int getRadius(){ return radius; }; //取得半径 int getUpperLeftX(){ return getX()-radius; }; //取得外接正方形左上角的X坐标

int getUpperLeftY(){ return getY()+radius; }; //取得外接正方形左上角的Y坐标 };

void main() {

Circle c;

c.setPoint(200, 250); c.setRadius(100);

cout<<\"X=\"<//e8_4.cpp

#include #include

class person {

char m_strName[10]; int m_nAge; public:

person(char * name,int age ) {

strcpy (m_strName,name); m_nAge = age;

cout<<\"constructor of person\"<~person() {

cout<<\"destrutor of person\"<class Employee:public person {

char m_strDept[20]; person Wang; public:

Employee(char * name,int age,char * dept,char age1):person(name,age),Wang(name1,age1) {

strcpy(m_strDept,dept);

cout<<\"constructor of Employee\"<~Employee(){cout<<\"constructor of Employee\"<void main() {

Employee emp(\"张三\人事处\王五\}

//e8_5.cpp

#include class A {

private: int a; public:

void setA(int x){ a = x; }

void showA(){cout<<\"a=\"<class B

* name1,int

{

private: int b; public:

void setB(int x){ b = x; }

void showB(){cout<<\"b=\"<class C:public A,private B //公有继承A,私有继承B {

private: int c; public:

void setC(int x,int y) {

c = x;

setB(y); //通过B类的成员函数setB()为B类的私有成员b赋值 }

void showC() {

showB(); //此处可以使用showB() cout<<\"c=\"<void main() {

C obj;

obj.setA(53);

obj.showA(); //输出a=53 obj.setC(55,58);

obj.showC(); //输出b=58 c=55 }

//e8_6.cpp

#include class Base1 {

private: int a; public:

Base1(int i){ a = i; cout<<\"constructing base a=\"<cout<<\"destroying base a=\"<};

class Base2 {

private: int b; public:

Base2(int i){ b = i; cout<<\"constructing base b=\"<cout<<\"destroying derived b=\"<class Derived:public Base1,public Base2 {

private: int c;

Base1 member; public:

Derived(int i,int j,int m,int n); ~Derived() {

cout<<\"destroying derived c=\"<Derived::Derived(int i,int j,int m,int n):Base1(i),Base2(j),member(m) {

c = n;

cout<<\"constructing derived c=\"<void main() {

Derived d(5,8,9,12); }

//e8_7.cpp

#include class Base1 {

public:

void print() {

cout<<\" Base1\"<class Base2

{

public:

void print() {

cout<<\" Base2\"<class Derived:public Base1,public Base2 {

public:

void print() {

cout<<\" Derived \"<void main() {

Derived d; d.print();

d.Base1::print(); d.Base2::print(); }

//e8_8.cpp

#include #include

class Person //人员类 ---- 虚基类 {

protected: char * name; int age;

Person() //缺省构造函数 ---- 从未被调用 {

cout<<\" Person 的缺省构造函数被调用 \\n\"; } public:

Person(char * n, int a):name(n), age(a) //完整的构造函数 {

cout<<\" Person 的构造函数被调用 \\n\"; }

~Person() //析构函数 {

cout<<\" Person 的析构函数被调用 \\n\"; } };

class Student:virtual public Person //学生类 ---- 虚基类的直接派生类 {

private:

char * specialty; protected:

//Student 类的自身构造函数;在Student 类作为中间派生类时,调用此构造函数,只初始化本//类的数据成员

Student(char * s): specialty(s) { cout<<\" Student 自身的构造函数被调用 \\n\"; } public:

//Student 类的完整构造函数;在创建 Student 类的对象时, 调用此构造函数 Student(char * n,int a,char * s) : Person(n,a),specialty(s) { cout<<\" Student 的完整构造函数被调用 \\n\"; } ~Student() //析构函数 { cout<<\" Student 的析构函数被调用 \\n\"; } void show() {

cout<<\"\\n名字 : \"<class Staff:virtual Person //职员类 ---- 虚基类的直接派生类 {

protected:

char * department;

//Staff 类的自身构造函数;在Staff 类作为中间派生类时,调用此构造函数,只初始化本类//的数据成员

Staff(char * d) {

department = d;

cout<<\" Staff 自身的构造函数被调用 \\n\"; } public:

//Staff 类的完整构造函数;在创建 Staff 类的对象时,调用此构造函数 Staff(char * n,int a,char * d):Person(n,a),department(d) {

cout<<\" Staff 的完整构造函数被调用 \\n\"; }

~Staff() //析构函数 {

cout<<\" Staff 的析构函数被调用 \\n\"; }

void show() {

cout<<\"\\n 名字 : \"<};

class Professor:public Staff //教授类 ---- 公有继承 Staff 类 {

private: int level; public:

//完整构造函数

Professor(char * n, int a, char * d, int h):Person(n, a), Staff(d), level(h) {

cout<<\" Professor 的构造函数被调用 \\n\"; }

~Professor() //析构函数 {

cout<<\" Professor 的析构函数被调用 \\n\"; }

void show() {

Staff::show(); cout<<\" 级别 : \"<class G_Student:public Student,public Staff//研究生类----公有继承 Student 类 {

public:

//完整构造函数

G_Student(char * n,int a,char * s,char * d): Person(n,a),Student(s),Staff(d) {

cout<<\" G_Student 的构造函数被调用\"; }

~G_Student() //析构函数 {

cout<<\" G_Student 的析构函数被调用 \\n\"; }

void show() {

Student::show();

cout<<\" 部门 : \"<void main() {

Student myStudent(\"Wang Yi\ Staff myStaff(\"Tang An\

Professor myProfessor(\"Chen Wu\

G_Student myGraduateStudent(\"Liu San\

myStudent.show(); myStaff.show(); myProfessor.show();

myGraduateStudent.show(); } //8-9

//employee.h class employee {

protected:

char * name;

int individualEmpNo; int grade;

float accumPay;

static int employeeNo; public:

employee(); ~employee(); void pay();

void promote(int); void displayStatus(); };

class technician:public employee {

private:

float hourlyRate; int workHours; public:

technician(); void pay();

void displayStatus(); };

class salesman:virtual public employee {

protected:

float CommRate; float sales; public:

salesman(); void pay();

void displayStatus(); };

class manager:virtual public employee {

protected:

float monthlyPay; public:

manager(); void pay();

void displayStatus(); };

class salesmanager:public manager,public salesman {

public:

salesmanager(); void pay();

void displayStatus(); };

//empfunc.cpp

#include #include #include \"employee.h\"

int employee::employeeNo = 1000; employee::employee() {

char namestr[50];

cout<<\"请输入下一个雇员的姓名:\"; cin>>namestr;

name = new char[strlen(namestr)+1]; strcpy(name,namestr);

individualEmpNo = employeeNo++; grade = 1;

accumPay = 0.0; }

employee::~employee() {

delete name; }

void employee::pay() {}

void employee::promote(int increment) {

grade += increment; }

technician::technician() {

hourlyRate = 100; }

void technician::pay() {

cout<<\"请输入\"<>workHours;

accumPay = hourlyRate * workHours;

cout<<\"兼职技术人员\"<void technician::displayStatus() {

cout<<\"兼职技术人员\"<salesman::salesman() {

CommRate = 0.004; }

void salesman::pay() {

cout<<\"请输入\"<>sales;

accumPay = sales * CommRate;

cout<<\"推销员\"<void salesman::displayStatus() {

cout<<\"推销员\"<manager::manager() {

monthlyPay = 8000; }

void manager::pay() {

accumPay = monthlyPay;

cout<<\"经理\"<void manager::displayStatus() {

cout<<\"经理\"<salesmanager::salesmanager()

{

monthlyPay = 5000; CommRate = 0.005; }

void salesmanager::pay() {

accumPay = monthlyPay;

cout<<\"请输入\"<>sales;

accumPay = monthlyPay + sales * CommRate;

cout<<\"销售经理\"<void salesmanager::displayStatus() {

cout<<\"推销经理\"<//e8_9.cpp

#include #include \"employee.h\" int main() {

manager m1; technician t1; salesmanager sm1; salesman s1; m1.promote(3); m1.pay();

m1.displayStatus(); cout<t1.displayStatus(); cout<sm1.displayStatus(); cout<s1.displayStatus(); return 0; }

第9章 多态性与虚函数

//e9_1.cpp

#include #include class Student {

protected:

int number; char * name; public:

Student (int a,char * b) {

number = a;

name = new char[strlen(b)]; strcpy(name, b); }

void print() //一般成员函数 {

cout<<\" 我的学号是 : \"<cout<<\" 我的名字是 : \"<class Smallstudent : public Student {

public:

Smallstudent(int a,char * b, float c):Student(a,b),averScore(c){} void print() {

cout<<\" 我的名字是:\"<private:

float averScore; };

void main() {

Student * pt; //pt是基类指针

Student x(101,\"王明\"); //创建Student类对象x

x.print(); //调用x对象的成员函数print()

pt = &x; //将基类指针pt指向Student 类对象 pt->print(); //调用成员函数print()

Smallstudent y(102,\"李四\创建Smallstudent 类对象y y.print(); //调用y对象的成员函数print() pt = &y; //用一个父类指针指向一个子类对象 pt->print(); //通过父类指针调用成员函数print() }

//e9_2.cpp

#include

class Pet //宠物类 {

public:

void Speak() {

cout<<\"How does a pet speak?\"<class Cat:public Pet {

public:

void Speak() {

cout<<\"miao!miao!\"<class Dog:public Pet {

public: void Speak() {

cout<<\"wang!wang!\"<void main() {

Pet * p1,* p2,* p3,obj; Dog dog1; Cat cat1;

obj = dog1; //子类对象赋给一个基类对象 obj.Speak();

p1 = &cat1; //用一个能够指向基类对象的指针变量指向一个子类对象 p1->Speak();

p1 = &dog1; //用一个能够指向基类对象的指针变量指向一个子类对象 p1->Speak();

p2 = new Cat;//用一个指向基类对象的指针变量指向一个动态生成的子类对象 p2->Speak(); p3 = new Dog; p3->Speak();

Pet &p4 = cat1;//以一个子类对象初始化一个基类的引用 p4.Speak(); }

//e9_3.cpp

#include #include class Student {

protected:

int number; char * name; public:

Student (int a,char * b) {

number = a;

name = new char[strlen(b)]; strcpy(name, b); }

virtual void print() //虚函数 {

cout<<\" 我的学号是 : \"<class Smallstudent : public Student {

public:

Smallstudent(int a,char * b, float c):Student(a,b),averScore(c){} void print() {

cout<<\" 我的名字是 : \"<cout<<\" 我的平均分数是 : \"<private:

float averScore; };

void main() {

Student * pt;

Student x(103,\"张海\"); x.print(); pt = &x; pt->print();

Smallstudent y(104,\"黎明\y.print(); pt = &y; pt->print();

}

//e9_4.cpp

#include class A {

public:

A(int i=3){ data = i; }//不能使用关键字 virtual将构造函数说明为虚函数 virtual void print(); //虚函数print不能说明为静态函数 private:

int data; };

//类体内定义的虚函数是非内联函数;即使在类外用inline说明它是内联函数,它仍然被编译器作为非内联函数来处理 inline void A::print() {

cout<<\"在基类中. \"<<\"data= \"<class B : public A {

public:

B(int i, int j):A(i),dba(j){}

//在基类A中, 函数print()是虚函数;下面,使用关键字 \"static\" 说明函数print是静态的。这个print函数与基类中的虚函数print无关,因此不能实现多态性 static void print(){ cout<<\" 在派生类中 \"<void main() {

A * pt; A b(10); pt = &b;

pt->print(); //调用A类中的虚函数print B c(20,15); pt = &c;

pt->print(); //还是调用A类中的虚函数print }

//e9_5.cpp

#include class Pet {

public:

virtual void Speak() {

cout<<\"How does a pet speak ?\"<class Cat:public Pet {

public:

virtual void Speak() {

cout<<\"miao!miao!\"<class Dog:public Pet {

public:

virtual void Speak() {

cout<<\"wang!wang!\"<void main() {

Pet * p1, * p2, * p3,obj; Dog dog1; Cat cat1;

obj = dog1; //obj.Speak(); //How does a pet speak ? p1 = &cat1;

p1->Speak(); //miao!miao! p1 = &dog1;

p1->Speak(); //wang!wang! p2 = new Cat;

p2->Speak(); // miao!miao! p3 = new Dog;

p3->Speak(); //wang!wang! Pet &p4 = cat1;

p4.Speak(); //miao!miao! delete p2; delete p3; }

//e9_6.cpp

#include class A {

public:

用Dog类对象给Pet类对象赋值 A(){ a = new char[10]; }

~A() //非虚析构函数 {

delete[] a;

cout<<\"基类中的析构函数\"<private:

char * a; };

class B: public A {

public:

B(){ b = new char[20]; } ~B() {

delete[] b;

cout<<\"派生类中的析构函数\"<char * b; };

void foo() {

A * k = new B; delete k; }

void main() {

foo(); }

//e9_8.cpp

#include class A {

public:

A(int i = 3){ x = i; } virtual void at() {

cout<<\"x=\"<void at2() {

at(); }

protected: int x; };

class B: public A {

public:

B(int m){ y = m; } void at() {

cout<<\"y=\"<void main() {

A k(5),* p; //p为基类指针 p = &k; //p指向基类对象k

p->at2(); //调用基类成员函数at2 B s(8);

p = &s; //基类指针p指向派生类对象s p->at2(); //调用基类成员函数at2 }

//e9_9.cpp

#include class A {

public:

A(){ fvd(); } //这里调用的都是A::fvd() virtual void fvd() {

cout<<\"基类中的成员函数\"<class B:public A {

public: void fvd() {

cout<<\"派生类中的成员函数\"<void bar() {

A * a=new B; //基类指针指向子类对象 delete a; }

void main() {

bar(); A a; B b; }

//e9_10.cpp

#include class Shape {

public:

virtual void area() = 0; //纯虚函数 };

class Circle : public Shape {

private: float r; public:

Circle(float r1){ r = r1; } void area() {

cout<<\" 圆的半径 : \"<cout<<\" 圆的面积 : \"<class Rectangle : public Shape {

public:

Rectangle(float a, float b) {

H = a; W = b; }

void area() {

cout<<\" 矩形的边长 : \"<protected: float H,W; };

void main() {

Shape * p; //用抽象类Shpae定义指针p

Circle a(5.0); //Circle 类是具体类, 创建对象a Rectangle b(2.0, 4.0); //Rectangle类是具体类,创建对象b p = &a; //抽象类指针指向Circle 类对象a p->area(); //调用纯虚函数area

p = &b; //抽象类指针指向Rectangle 类对象b p->area(); }

//e9_11.cpp

#include class Employee {

public:

Employee(char nm[],int id) { name = nm;ID = id; } ~Employee(){};

int getid(){return ID;}

char * getname(){return name;} void setid(int id){ ID = id;}

void setname(char nm[]){name = nm;} virtual int pay() = 0; virtual void print() = 0; protected:

char * name; int ID; };

class Manager:public Employee {

public :

Manager(char nm[],int id,int sl):Employee(nm,id) { sal = sl; } ~Manager(){};

int getsal(){return sal;}

void setsal(int sl){ sal = sl; } int pay(){return sal;} void print() {

cout<protected: int sal; };

class Hourlyworker:public Employee {

public:

Hourlyworker(char nm[],int id,int w,int h):Employee(nm,id) { wage = w; hours = h; } ~Hourlyworker(){};

int getwage(){return wage;}

void setwage(int w){ wage = w; } int gethours(){return hours;}

void sethours(int h){ hours = h; } int pay(){return hours*wage;} void print() {

cout<<\"\\nname:\"<protected: int wage ; int hours; };

void main() {

Manager manag(\"zhang\

Hourlyworker hourw(\"li\ manag.print (); hourw.print(); }

第10章 运算符重载与类模板 //e10_1.cpp

#include \"iostream.h\" class Complex {

private:

double real,imag; //实部real和虚部imag public:

Complex(){ real = imag = 0; }

Complex(double r,double i = 0) //虚部可以省略 {

real = r; imag = i; }

Complex add(Complex & r) //加法函数 {

this->real += r.real;

this->imag += r.imag;

return Complex(this->real,this->imag); }

friend void print(Complex & c); //友元函数 };

void print(Complex & c) {

cout<void main( ) {

Complex c1(2.0,3.0),c2(4.0,-2.0),c3(5.0,1.0),c4; c4 = c1.add(c2).add(c3); //复数相加 print(c4); }

//e10_2.cpp

#include \"iostream.h\" class Complex {

private:

double real,imag; public:

Complex(){ real = imag = 0; }

Complex(double r, double i = 0) //虚部可以省略 {

real = r; imag = i; }

Complex operator +(Complex & c) //重载+运算符 {

//构造一个复数, 使之等于两复数之和,并把它作为函数返回值 return Complex(real + c.real,imag + c.imag); }

friend void print(Complex & c); };

void print(Complex & c) {

cout<void main() {

Complex c1(2.0,3.0),c2(4.0,-2.0),c3(5.0,1.0),c4; c4 = c1+c2+c3; //复数相加 print(c4);

}

//e10_3.cpp

#include \"iostream.h\" class Complex {

private:

double real,imag; public:

Complex() { real = imag = 0; }

Complex(double r,double i = 0) //虚部可以省略 {

real = r; imag = i; }

friend Complex operator +(Complex & c1,Complex & c2); //重载+运算符 friend void print(Complex & c1); };

Complex operator +(Complex & c1,Complex & c2) //重载+运算符 {

//构造一个复数, 使之等于两复数之差,并把它作为函数返回值 return Complex(c1.real + c2.real,c1.imag + c2.imag); };

void print(Complex & c) {

cout<void main() {

Complex c1(2.0,3.0),c2(4.0,-2.0), c3(5.0,1.0),c4;

c4 = c1+c2+c3; //复数相加 print(c4); }

//e10_4.cpp

#include #include #include

class Complex //Complex是复数 {

private:

double real; //real为实部 double imag; //imag为虚部 public:

Complex(double r = 0, double i = 0) //带默认参数值的构造函数 {

real = r;

imag = i; //对real和imag赋值 }

void print(); //成员函数print显示real和imag

void operator =(Complex &); //赋值操作 friend Complex operator -(const Complex &); //单目-操作 //双目 + 操作

friend Complex operator +(const Complex & c1, const Complex & c2); //双目 - 操作

friend Complex operator -(const Complex & c1, const Complex & c2); //双目 * 操作

friend Complex operator *(const Complex & c1, const Complex & c2); //双目 / 操作

friend Complex operator /(const Complex & c1, const Complex & c2); friend double norm(const Complex &); //单目操作,求复数的幅值的平方 };

void Complex::print() {

cout<<'('<void Complex::operator =(Complex & c) {

real = c.real; imag = c.imag; }

Complex operator -(const Complex & c) {

return Complex(-c.real,-c.imag); }

Complex operator +(const Complex & c1, const Complex & c2) {

double r = c1.real + c2.real; double i = c1.imag + c2.imag; return Complex(r,i); }

Complex operator -(const Complex & c1, const Complex & c2) {

double r = c1.real - c2.real; double i = c1.imag - c2.imag; return Complex(r,i); }

Complex operator *(const Complex & c1, const Complex & c2) {

double r = c1.real * c2.real - c1.imag * c2.imag; double i = c1.real * c2.imag + c1.imag * c2.real;

return Complex(r,i); }

Complex operator /(const Complex & c1, const Complex & c2) {

Complex result; double den; den = norm(c2);

if(den>1E-7||den<-1E-7) {

result.real = ((c1.real * c2.real) - (c1.imag * c2.imag))/den; result.imag = ((c1.real * c2.real) + (c1.imag * c2.imag))/den; } else {

cout<<\" complex / error ! \"<return result; }

double norm(const Complex & c) {

double result = (c.real * c.real) + (c.imag * c.imag); return result; };

void main() {

Complex c1(2.5,3.5),c2(4.5,6.5); //复数 c1 = 2.5+i3.5; c2 = 4.5+i6.5 Complex c; c = c1 - c2; c.print(); c = c1 + c2; c.print(); c = c1 * c2; c.print(); c = c1 / c2; c.print(); }

//e10_5.cpp

#include \"iostream.h\" class Fraction {

private:

int nume,deno; public:

Fraction(int z = 0,int m = 1 ) {

deno = m; nume = z; }

Fraction operator ++() //重载前增1运算符 {

nume = nume + deno; return *this; }

Fraction operator ++(int i) //重载后增1运算符 {

nume = nume + deno;

return Fraction(nume - deno,deno); }

Fraction operator --() //重载前减1运算符 {

nume = nume - deno; return *this; }

Fraction operator --(int i) //重载后减1运算符 {

nume = nume - deno;

return Fraction(nume + deno,deno); }

friend void print(Fraction & r); };

void print(Fraction & r) {

cout<<\" \"<void main() {

Fraction c1(2,5); print(c1); print(c1++); print(++c1); print(--c1); print(c1--); print(c1); }

//e10_6.cpp

#include \"iostream.h\" class Fraction

{

private:

int nume,deno; public:

Fraction( int z = 0,int m = 1 ) {

deno = m; nume = z; }

int operator >(Fraction & r) {

if(nume * r.deno > deno * r.nume) return 1; else

return 0; }

friend void print(Fraction & r); };

void print(Fraction & r) {

cout<<\" \"<void main() {

Fraction c1(2,5); Fraction c2(4,7); if(c1>c2) {

print(c1); } else {

print(c2); } }

//e10_7.cpp

#include \"iostream.h\" class Fraction {

private:

int nume,deno; public:

Fraction (int z = 0,int m = 1 ) {

deno = m; nume = z; }

Fraction & operator ++() //重载前增1运算符 {

nume = nume+deno; return *this; }

Fraction operator ++(int i) //重载后增1运算符 {

nume = nume+deno;

return Fraction(nume - deno,deno); }

Fraction & operator --() //重载前减1运算符 {

nume = nume-deno; return *this; }

Fraction operator --(int i) //重载后减1运算符 {

nume = nume-deno;

return Fraction(nume+deno,deno); }

friend void print(Fraction & r); int MaxSubmultiple(int a,int b) {

int r; if( b>a ) {

r = a; a = b; b = r; }

r = a % b; while( r>0 ) {

a = b; b = r; r = a % b; }

return b; }

void operator +=( Fraction & r) {

int x;

x = deno * r.deno / MaxSubmultiple(deno,r.deno); nume = nume * x/deno + r.nume * x/r.deno; deno = x; } };

void print(Fraction & r) {

cout<void main() {

Fraction c1(2,5); Fraction c2(3,10); c1 += c2; print(c1); }

//e10_8.cpp

#include \"iostream.h\" class Array {

private:

int length; //长度 int * firstAddress; //首地址 public:

Array(){} Array(int i) {

length = i;

firstAddress = new int[length]; }

int & operator [](int i) //重载下标运算符(返回第i个元素) {

if( i<0||i>=length ) //检查下标是否越界 {

cerr<<\"fata:Index out of range\\n\"; }

return *(firstAddress+i); }

void operator =(Array & b) //重载=运算符 {

length = b.length;

firstAddress = b.firstAddress; }

void setVectorPointer(int * p) //设置数组的首地址 {

firstAddress = p; }

friend ostream & print(Array &); };

ostream & print(Array & x) {

for(int i=0; ivoid print(Fraction & r) {

cout<<\" \"<void main() {

Array a; a=Array(10);

for(int i=0; i<11; i++) {

a[i]=i; }

print(a); }

//e10_9.cpp

#include \"iostream.h\"

int MaxSubmultiple(int a,int b) {

int r; if(b>a) {

r = a; a = b; b = r; }

r = a % b; while( r>0 ) {

a = b;

b = r; r = a % b; }

return b; }

class Fraction {

private:

int nume,deno; public:

friend ostream & operator <<(ostream & ostr,Fraction & r); Fraction (int z = 0,int m = 1 ) {

deno = m; nume = z; }

void operator +=( Fraction & r) {

int x;

x = deno * r.deno/MaxSubmultiple(deno,r.deno); nume = nume * x/deno + r.nume * x/r.deno; deno = x; } };

ostream & operator <<(ostream & ostr,Fraction & r) {

cout<void main() {

Fraction c1(2,5); Fraction c2(3,10); c1 += c2; cout<//e10_10.cpp

#include \"iostream.h\"

int MaxSubmultiple(int a,int b) {

int r; if( b>a ) {

r = a; a = b; b = r; }

r = a % b; while( r>0 ) {

a = b;

b = r; r = a % b; }

return b; }

class Fraction {

private:

int nume,deno; public:

friend ostream & operator <<(ostream &, Fraction &); friend istream & operator >>(istream &, Fraction &); Fraction (int z = 0,int m = 1 ) {

deno = m; nume = z; }

void operator +=( Fraction & r) {

int x;

x = deno * r.deno/MaxSubmultiple(deno,r.deno); nume = nume * x/deno + r.nume * x/r.deno; deno = x; } };

ostream & operator <<(ostream & ostr, Fraction & r) {

cout<istream & operator >>(istream & istr, Fraction & r) {

cout<<\"分子=\"; istr>>r.nume; cout<<\"分母=\"; istr>>r.deno; return istr; }

void main() {

Fraction c1(2,5); Fraction c2; cin>>c2; c1 += c2; cout<//e10_11.cpp

#include \"iostream.h\" class TRangeInt {

private:

int value; public:

TRangeInt(int v = 0) {

value = v; }

operator int() {

return value; } };

void main() {

TRangeInt tr1(5),tr2(15),tr3(8),tr4; tr4 = TRangeInt(tr1 + tr2 - tr3); cout<//e10_12.cpp

#include \"iostream.h\" class Vector; class Complex {

private:

double real; //real为实部 double imag; //imag为虚部 public:

Complex(double r = 0,double i = 0) {

real = r; imag = i; }

friend ostream & operator <<(ostream & ostr,Complex & c); operator Vector();

};

class Vector {

private:

double x,y; public:

Vector(double tx = 0,double ty = 0) {

x = tx; y = ty; }

operator Complex();

friend ostream & operator <<(ostream & ostr,Vector & v); };

ostream & operator <<(ostream & ostr,Complex & c) {

ostr<ostream & operator <<(ostream & ostr,Vector & v) {

ostr<<\"(\"<Vector::operator Complex() {

return Complex(x,y); }

Complex::operator Vector() {

return Vector(real,imag); }

void main() {

Vector v(2.5,3.1); Complex c;

c = Complex(v); cout<Complex c1(2.5,8.3); Vector v1;

v1 = Vector(c1); cout<}

//e10_13.cpp

#include \"iostream.h\" class Vector; class Complex {

private:

double real; //real为实部 double imag; //imag为虚部 public:

Complex(double r = 0,double i = 0) {

real = r; imag = i; }

double getReal() {

return real; }

double getImag() {

return imag; }

friend ostream & operator <<(ostream & ostr,Complex & c); Complex(Vector); };

class Vector {

private:

double x,y; public:

Vector(double tx = 0,double ty = 0) {

x = tx; y = ty; }

double getx() {

return x; }

double gety() {

return y; }

Vector(Complex);

friend ostream & operator <<(ostream & ostr,Vector & v); };

ostream & operator <<(ostream & ostr,Complex & c) {

ostr<ostream & operator <<(ostream & ostr,Vector & v) {

ostr<<\"(\"<Complex::Complex(Vector v) {

real=v.getx(); imag=v.gety(); }

Vector::Vector(Complex c) {

x = c.getReal(); y = c.getImag(); }

void main() {

Vector v(2.5,3.1); Complex c;

c = Complex(v); cout<Complex c1(2.5,8.3); Vector v1;

v1 = Vector(c1); cout<//e10_14.cpp

#include \"iostream.h\"

template class List {

protected:

struct Node {

Node * pNext;

T * pT; };

Node * pFirst; public: List() {

pFirst = 0; }

void Add(T & t) {

Node * temp = new Node; temp->pT = &t;

temp->pNext = pFirst; pFirst = temp; }

void Remove(T & t) {

Node * temp = 0;

if( *(pFirst->pT)==t ) {

temp = pFirst;

pFrist = pFirst->pNext; } else {

for(Node * p = pFirst; p->pNext; p = p->pNext) if( *(p->pNext->pT )==t) {

temp = p->pNext;

p->pNext = temp->pNext; break; } }

if(temp) {

delete temp->pT; delete temp; } }

T * Find(T & t) {

for(Node * p = pFirst; p->pNext; p = p->pNext) {

if( *(p->pT)==t )

return p->pT; }

return 0; }

void Printlist() {

for(Node * p = pFirst; p->pNext; p = p->pNext) cout<<*(p->pT)<<\" \"; cout<~List() {

Node * p;

while( p=pFirst ) {

pFirst = pFirst->pNext; delete p->pT; delete p; } } };

void main() {

List floatlist; for(int i=1; i<7; i++)

floatlist.Add( *new float(i + 0.6) ); floatlist.Printlist(); float b = 3.6;

float * pa = floatlist.Find(b); if(pa)

floatlist.Remove( *pa ); floatlist.Printlist(); }

//e10_15.cpp

#include class Matrix {

public:

friend Matrix operator +( Matrix &, Matrix & ); //矩阵相加 friend Matrix operator -( Matrix &, Matrix & ); //矩阵相减 friend Matrix operator *( Matrix &, Matrix & ); //矩阵相乘

Matrix (int row,int col); //构造一个具有row行col列的矩阵 Matrix (Matrix & src); //定义一个拷贝构造函数 ~Matrix(){ delete []mem; } //析构函数

void print(); //输出矩阵内容 int GetRows()const{ return rows; } //取行数 int GetCols()const{ return cols; } //取列数 int & operator()(int i,int j); //重载() Matrix operator =( Matrix & src ); //重载= Matrix operator -(); //重载取负- Matrix operator ++(); //重载前缀++ Matrix operator ++(int); //重载后缀++ private:

int * mem;

const int rows,cols; };

Matrix::Matrix(int row,int col):rows(row),cols(col) //构造函数 {

mem = new int[row * col]; }

Matrix::Matrix(Matrix &src):rows(src.rows),cols(src.cols)//拷贝构造函数 {

mem = new int[src.rows * src.cols];

for(int i=0; ivoid Matrix::print() {

for(int i=0; ifor(int j=0; jcout<cout<Matrix operator +(Matrix & m1,Matrix & m2) {

Matrix m3(m1.rows,m1.cols); //临时矩阵 for(int i=0; iMatrix operator -(Matrix & m1,Matrix & m2) {

Matrix m3(m1.rows,m1.cols); for(int i=0; ifor(int j=0; jMatrix operator *(Matrix & m1,Matrix & m2) {

Matrix m3(m1.rows,m2.cols); int sum;

for(int i=0; isum = 0;

for(int k=0; kreturn m3; }

Matrix Matrix::operator -() {

Matrix m(rows,cols); //临时对象 for(int i=0; iMatrix Matrix::operator ++() //前缀++ {

for(int i=0; iMatrix Matrix::operator ++(int) //后缀++ {

Matrix m(*this); //构造一个和当前矩阵一样的临时矩阵 for(int i=0; ireturn m; //返回的是原来的矩阵 }

Matrix Matrix::operator =(Matrix & src) {

for(int i=0; imem[i] = src.mem[i]; return *this; }

int & Matrix::operator()(int i,int j) {

return mem[i * cols + j]; }

void main() {

Matrix m1(3,3),m2(3,3),m3(3,3); int i ,j;

for(i=0; i<3; i++) for(j=0; j<3; j++)

m1(i,j) = m2(i,j) = i+j; cout<<\"m1:\"<cout<<\"m2:\"<cout<<\"m1+m2:\"<cout<<\"m1-m2:\"<cout<<\"m1*m2:\"<cout<<\"++m1:\"<cout<<\"before m1++\"<cout<<\"after m1++\"<cout<<\"-m1:\"<//e10_16.cpp

#include #include template class Array {

private:

T * set; int n; public:

Array(T * data,int i){ set = data;n = i; } ~Array(){}

void sort(); //排序

int seek(T key); //查找指定的元素 T sum(); //求和

void disp(); //显示所有的元素 };

template void Array::sort() {

int i,j; T temp;

for(i=1; i=i; j--) if(set[j-1]>set[j])

{temp = set[j-1];set[j-1] = set[j];set[j] = temp;} }

template

int Array::seek(T key) {

int i;

for(i=0; itemplate T Array::sum() {

T s=0; int i;

for(i=0; itemplate void Array::disp() {

int i;

for(i=0; i}

void main() {

int a[] = {6,3,8,1,9,4,7,5,2};

double b[] = {2.3,6.1,1.5,8.4,6.7,3.8}; Arrayarr1(a,9); Arrayarr2(b,6); cout<<\" arr1:\"<cout<<\" 原序列:\"; arr1.disp();

cout<<\" 8在arr1中的位置:\"<cout<<\" 排序后:\"; arr1.disp(); cout<<\"arr2:\"<cout<<\" 原序列:\"; arr2.disp();

cout<<\" 8.4在arr2中的位置:\"<cout<<\" 排序后:\"; arr2.disp(); }

第11章 流 //e11_1.cpp

#include void main() {

int i = 8;

float j = 5.5; double k = 78.9; char * s = \"Hello\";

cout<<\"i = \"<cout<<\"k= \"<//e11_2.cpp

#include void main() {

int m; float n; char s[10];

cout<<\"请依次输入一个整数和一个单精度数:\"; cin>>m>>n;

cout<< \"请依次输入一个字符串:\"; cin>>s;

cout<< \"m= \"<//e11_3.cpp

#include void main() {

char ch;

while( (ch = cin.get())!='/n' ) cout.put(ch); }

//e11_4.cpp

#include void main() {

char a[80],b[80] ,c[80] ,d[20]; cout<<\"请键入一个字符:\";

cout<cout<<\"请输入一行字符串:\";

for(int i=0; i<80; i++) //与for循环结合在一起实现字符串的输入 {

a[i] = cin.get(); if( a[i] == '\\n' ) {

a[i] = '\\0'; break; } }

cout<cout<<\"请输入一行字符串:\"; cin.get(b,80) ;//有三个参数的get函数,当遇到行结束字符(默认值为'/n')或输入80个字符就结束 cout<cout<<\"请输入一行字符串:\";

cin.getline(c,80); //用getline()函数接收字符串 cout<cout<<\"请输入一行字符串:\";

cin.read(d,10); //输入包含10个字符的字符串 cout.write(d,7); //输出字符串中前5个字符 cout<//e11_5.cpp

#include void main() {

char a[20]; char ch;

cout<<\"请输入一个字符串:\";

cin.ignore( 5); //跳过输入流中的5个字符 cin.getline(a,20); cout<cout<<\"请输入一个字符:\"; ch = cin.get(); cout<cin.putback(ch); //最后一次用函数get,从输入流提取的字符放回到输入流中 cout<//e11_6.cpp

#include #include void main() {

int a=28;

double b=3.4567; cout<<\"a=\"<cout<<\"a=\"<cout<<\"b=\"<cout<<\"a=\"<//e11_7.cpp

#include #include

ostream & fprint(ostream & stream) {

stream.setf(ios::left);

stream<void main() {

cout<<28<<\" \"<//e11_8.cpp

#include #include void main() {

const double pi=3.14159; double r=5,c,s; c = 2.0 * pi * r; s = pi * r * r;

cout<<\"圆的周长(小数)为:\"<cout<<\"圆的面积(小数)为:\"<cout<<\"圆的周长(指数)为:\"<cout<//e11_9.cpp

#include void main() {

cout.width(6); //只对随后一个数的输出域宽起作用 cout<<123<<3.145<cout<cout.precision(3);

cout<<123<cout<cout.setf(ios::fixed, ios::floatfield); //今后以定点格式显示浮点数(无指数部分)

cout.width(6); cout.precision(3);

//当格式为ios::fixed时,设置小数点后的位数为3 cout<<123<//e11_10.cpp

#include #include void main() {

for(int n=1; n<5; n++) {

cout<} }

//e11_11.cpp

#include #include #include void main() {

int n;

double b = sqrt(3.0); cout<<\"请输入一个整数:\"; cin>>n;

cout<cout<for(int i=0; i<5; i++) {

cout.precision(i); cout<cout<<\"Precision set by the setprecision manipulator:\"<cout<//e11_12.cpp

#include \"iostream.h\" #include \"fstream.h\" #include \"iomanip.h\" void main() {

ofstream outfile; ifstream infile;

int x; //用来存放读入的数据 outfile.open(\"test.txt\");

if(!outfile) //判断文件是否成功打开 {

cout<<\"文件打开失败!\"<cout<<\"请输入已列数字,以9999结束,如:123 34 9999\"<>x;

while(x!=9999) {

outfile<>x; }

cout<<\"数字已经写入文件!\\n\"; outfile.close();

infile.open(\"test.txt\");//存放整数的文件

if(!infile) //判断文件是否成功打开 {

cout<<\"打不开输入文件 test.txt \"<//从文件中读入整数并输出,直至文件尾,循环结束 while( infile>>x ) cout<cout<<\"\\n读入文件结束!\"<//e11_13.cpp

#include \"iostream.h\" #include \"fstream.h\" void main() {

char filename[255];

cout<<\"请输入要打开的文件名:\"; cin>>filename;

ifstream infile(filename); if(!infile) {

cout<<\"源文件打开失败!\"<cout<<\"请输入目标文件名:\"; cin>>filename;

ofstream outfile(filename); if(!outfile) {

cout<<\"打不开目标文件\"<char c;

while(!infile.eof()) //判断是否到文件尾 {

c=infile.get(); //读入一个字符并赋给c outfile.put(c); //写入一个字符 }

cout<<\"\\n文件复制完毕\\n\"; infile.close(); outfile.close(); }

//e11_14.cpp

#include \"iostream.h\" #include \"fstream.h\" #include \"String.h\" void main() {

ofstream outfile(\"stuInfo.txt\"); if(!outfile) {

cout<<\"输出文件stuInfo.txt打开失败!\"<cout<<\"请输入学生的个人信息,输入顺序为:\"<char * name = new char[20]; //用来存储名字 int No; //用来存储学号

cin>>name>>No; //从键盘输入姓名和学号 while(strcmp(name,\"exit\")) //判断是否输入了exit {

outfile<>name>>No; }

outfile.close();

cout<<\"\\n数据已经写入文件。\\n\"; delete []name; }

//e11_15.cpp

#include #include void main() {

char a[20]=\"Hello world!\"; struct student {

char name[20]; int age;

double score;

} ss={\"hao zi\

cout<<\"写入数据到‘c:\\\\Cfile.bin’文件\"<fout.write( (char *)(&Len), sizeof(int) ); fout.write(a, Len); //数据间无需分割符 fout.write((char *)(&ss), sizeof(ss)); fout.close();

cout<<\"--------------------------------------\"<ifstream fin(\"c:\\\\Cfile.bin\ fin.read( (char *)(&Len), sizeof(int) ); fin.read(b, Len); b[Len]='\\0';

fin.read( (char *)(&ss), sizeof(ss) ); cout<<\"Len=\"<cout<<\"ss=>\"<cout<<\"--------------------------------------\"<//e11_16.cpp

#include #include

struct student //定义结构体,包括学生的学号、姓名、成绩 {

char * number; char * name; float score;

}st[4]={{\"2008101\4\void main() {

fstream f1;

f1.open (\"c:\\\\data.dat\ if (!f1) {

cout<<\"不能打开文件!\"<for(int i=0; i<4; i++) //将学生的信息写入文件 f1.write((char *)&st[i],sizeof(student));

f1.seekp(sizeof(student)*2); //将文件指针定位到第3位同学

f1.read((char *)&s,sizeof(student)); //读取学生的信息 cout<f1.seekp(sizeof(student)*0); //将文件指针定位到第1位同学 f1.read((char *)&s,sizeof(student));

cout<f1.seekp(sizeof(student)*1,ios::cur); //将文件指针定位到第3位同学 f1.read((char *)&s,sizeof(student));

cout<f1.seekp(sizeof(student)*0,ios::cur); //将文件指针定位到第4位同学 f1.read((char *)&s,sizeof(student));

cout<//e11_17.cpp

#include #include void main() {

double ad = 3.1415926; int number = 2008;

cout<cout<cout<cout<//e11_18.cpp

#include #include #include void main() {

char ch;

ofstream tfile(\"c:\\\\hz.dat\"); if (!tfile) {

cerr<<\"c:\\\\hz.dat not open!\"<exit(1); }

cout<<\"要写入文件的内容(以ctrl+z结束):\"<tfile.put(ch); ch = cin.get(); }

tfile.close();

ifstream hfile(\"c:\\\\hz.dat\ if (!hfile) {

cerr<<\"c:\\\\hz.dat not open!\"<int i = 0;

while(hfile.get(ch)) {

cout<if(ch=='\\n ') i++; }

cout<第13章 综合实训 //goods.h

class Goods //商品类 {

private:

char name[20]; //商品名称 float price; //商品价格 int number; //商品数量 Goods * next; //下一种商品 public:

friend ostream & operator <<(ostream & out,Goods & goods); Goods(char * name,float price,int number); //构造函数 Goods * getNext(); char * getName();

void setNext(Goods * next);

void sale(char * name,int number); //商品销售 void add(char * name,int number); //商品上架 void showMe(); //商品信息显示

};

ostream & operator <<(ostream & out,Goods & goods); //goods.cpp

#include #include #include \"goods.h\"

Goods::Goods(char * name,float price,int number) {

strcpy(this->name,name); this->price = price; this->number = number; next = NULL; }

Goods * Goods::getNext() {

return next; }

char * Goods::getName() {

return name; }

void Goods::setNext(Goods * next) {

this->next = next; }

void Goods::sale(char * name,int number) {

if (this->numbercout<<\"名称为\"<this->number -= number;

cout<<\"名称为\"<cout<<\"名称为\"<number<void Goods::add(char * name,int number) {

this->number += number;

cout<<\"名称为\"<cout<<\"名称为\"<number<void Goods::showMe() {

cout<<(*this)<ostream & operator <<(ostream & out,Goods & goods) {

out<<\"商品名称:\"<//Supermarket.h #include \"goods.h\"

class Supermarket //超市类 {

private:

Goods * head; public:

Supermarket(); ~Supermarket();

void appendGoods(char * name,float price,int number); //商品添加 void queryAllGoods(); //查询所有商品 void deleteGoods(char * name); //商品删除 void saleGoods(char * name,int number); //商品销售 void addGoods(char * name,int number); //商品上架 void queryGoods(char * name); //查询指定商品 };

//Supermarket.cpp #include #include

#include \"supermarket.h\" Supermarket::Supermarket() {

head = NULL; }

Supermarket::~Supermarket() {

Goods * p;

while(head!=NULL) {

p = head;

head = head->getNext(); delete p; } }

void Supermarket::appendGoods(char * name,float price,int number) {

Goods* pNew = new Goods(name,price,number); Goods * p;

if (head==NULL) head = pNew; else {

p = head;

while(p->getNext()!=NULL) p = p->getNext(); p->setNext(pNew); } }

void Supermarket::queryAllGoods() {

Goods * p = head; while(p!=NULL) {

p->showMe();

p = p->getNext(); } }

void Supermarket::deleteGoods(char * name) {

Goods * p = head; Goods * q = head; if (p==NULL)

cout<<\"无任何商品,无法删除!\"<getName(),name)==0) {

p = p->getNext(); head = p; delete q;

cout<<\"已删除商品\"<p = p->getNext();

while((p!=NULL) && (strcmp(p->getName(),name)!=0)) {

q = p;

p = p->getNext(); }

if(p==NULL)

cout<<\"待删除商品\"<{

q->setNext(p->getNext());

cout<<\"已删除商品\"<void Supermarket::saleGoods(char * name,int number) {

Goods * p = head; if (p==NULL)

cout<<\"无任何商品,无法销售!\"<getName(),name)==0) p->sale(name,number); else {

p = p->getNext();

while((p!=NULL) && (strcmp(p->getName(),name)!=0)) p = p->getNext(); if(p==NULL)

cout<<\"待销售商品\"<p->sale(name,number); } }

void Supermarket::addGoods(char * name,int number) {

Goods * p = head; if (p==NULL)

cout<<\"无任何商品,无法上架!\"<getName(),name)==0) p->add(name,number); else {

p = p->getNext();

while((p!=NULL) && (strcmp(p->getName(),name)!=0)) p = p->getNext(); if(p==NULL)

cout<<\"待上架商品\"<p->add(name,number); } }

void Supermarket::queryGoods(char * name)

{

Goods * p = head; if (p==NULL)

cout<<\"无任何商品,无法查询!\"<getName(),name)==0) p->showMe(); else {

p = p->getNext();

while((p!=NULL) && (strcmp(p->getName(),name)!=0)) p = p->getNext(); if(p==NULL)

cout<<\"待查询商品\"<p->showMe(); } }

//pmain.h

void Append(); void Query(); void Sale(); void Add();

void QueryAll(); void Delete(); //pmain.cpp

#include #include \"pmain.h\"

#include \"supermarket.h\" Supermarket s; void main() {

int num; while(1) {

cout<<\"\商 品 管 理 系 统\"<cout<<\" 1-增加商品,\,4-商品销售\"<>num; switch(num) {

case 0:break;

case 1:Append();break; case 2:Delete();break; case 3:Query();break; case 4:Sale();break; case 5:Add();break;

case 6:QueryAll();break; }

if (num==0) break; } }

void Append() {

char name[20]; float price; int number; cout<cout<<\"请输入商品名称,价格,数量:\"; cin>>name>>price>>number;

s.appendGoods(name,price,number); cout<void Add() {

char name[20]; int number; cout<cout<<\"请输入待上架商品名称,数量:\"; cin>>name>>number;

s.addGoods(name,number); cout<void Sale() {

char name[20]; int number; cout<cout<<\"请输入待销售商品名称,数量:\"; cin>>name>>number;

s.saleGoods(name,number); cout<void QueryAll() {

cout<s.queryAllGoods(); cout<void Query() {

cout<cout<<\"请输入待查询商品名称:\"; cin>>name;

s.queryGoods(name); cout<void Delete() {

cout<cout<<\"请输入待删除商品名称:\"; cin>>name;

s.deleteGoods(name); cout<

因篇幅问题不能全部显示,请点此查看更多更全内容