第一章 C++的初步知识
//1.2 求和
void test1() {
int a, b, sum;
cin >> a >> b;
sum = a + b;
cout << "a+b=" << sum << endl;
}
//1.3 求最大值
int max(int x, int y) {
if (x > y) {
return x;
}
return y;
}
void test2() {
int a, b, m;
cin >> a >> b;
m = max(a, b);
cout << "max = " << m << endl;
}
//1.4 面向对象
class Student {
private:
int num;
int score;
public:
void setdata() {
cin >> num;
cin >> score;
}
void display() {
cout << "num = " << num << endl;
cout << "score = " << score << endl;
}
};
Student stud1, stud2;
void test3() {
stud1.setdata();
stud2.setdata();
stud1.display();
stud2.display();
}
第二章 数据类型与表达式
//2.1 字符赋给整型变量
void test2_1() {
int i, j;
i = 'A';
j = 'B';
cout << i << ' ' << j << '\n';
}
//2.2 小写字母变大写 a=97 A=65
void test2_2() {
char c1='a', c2='b';
c1 = c1 - 32;
c2 = c2 - 32;
cout << c1 << ' ' << c2 << '\n';
}
//2.4 强制类型转换
void test2_4() {
float x=3.6;
int i;
i = (int)x;
cout << "x=" << x << ",i=" << i << endl;
}
//2.5 将有符号数据传给无符号数据
void test2_5() {
unsigned short a;
short int b = -1;
a = b;
cout << "a=" << a << endl;
}
//2.6 逗号
void test2_6() {
int x, a;
x = (a = 3, 6 * 3);
cout <<"x="<< x << endl;
x = a = 3, 6 * a;
cout << "x=" << x << endl;
cout << (3 * 5, 43 - 6 * 5, 67 / 3) << endl;
}
第三章 程序设计初步
//3_1 各行小数点对齐
void test3_1() {
double a = 123.456, b = 3.14159, c = -3214.67;
cout << setiosflags(ios::fixed) << setiosflags(ios::right) << setprecision(2);//设置小数点后2为,右对齐
cout << setw(10) << a << endl; //10个字符
cout << setw(10) << b << endl;
cout << setw(10) << c << endl;
}
//3_2 输出单个字符 putchar
void test3_2() {
char a, b, c;
a = 'B', b = 'O', c = 'Y';
putchar(a);putchar(b);putchar(c);putchar('\n');
putchar(66);putchar(79);putchar(89);putchar(10);
}
//3_3 输入单个字符 getchar
void test3_3() {
char c;
//c = getchar();putchar(c + 32);putchar(10);
putchar(getchar() + 32);putchar(10);
}
//3_4 scanf printf 函数进行输入输出
void test3_4() {
int a;float b;char c;
scanf_s("%d %b %c", &a, &c, &b);
printf("a=%d,b=%f,c=%c\n", a, b, c);
}
//3_5 求ax^2+bx+c=0的根
void test3_5() {
float a, b, c, x1, x2;
cin >> a >> b >> c;
if (pow(b, 2) - 4 * a * c >= 0) {
x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
cout << "x1=" << x1 << endl;
cout << "x2=" << x2 << endl;
}
else {
cout << "没有解" << endl;
}
}
//3_6 求三角形面积
void test3_6() {
double a, b, c;
cout << "please enter a,b,c:";
cin >> a >> b >> c;
if (a + b > c&& b + c > a&& a + c > b) {
double s, area;
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
cout << setiosflags(ios::fixed) << setprecision(4);
cout << "area=" << area << endl;
}
else {
cout << "it is not trilateral" << endl;
}
}
//3_7 判断是否为大写,是:转小写 否:不动
void test3_7() {
char ch;
cin >> ch;
ch = (ch >= 'A' && ch < 'Z') ? ch + 32 : ch;
cout << ch << endl;
}
//3_8 判断某年是否为闰年
void test3_8() {
int year;
bool leap;
cout << "please enter year:";
cin >> year;
if (year % 4 == 0 && year % 100 != 0 || year % 100 == 0 && year % 400 == 0) {
leap = true;
}
else {
leap = false;
}
switch (leap) {
case 1:cout << "it is a leap year" << endl;break;
default:cout << "it is not a leap year" << endl;
}
}
//3_9 运输公司路程计费 p:运费/吨 w:重 s:距离 d:折扣 f:总运费 f=p*w*s*(1-d)
void test3_9() {
int c, s;
float p, w, d, f;
cout << "please enter p,w,s: ";
cin >> p >> w >> s;
if (s >= 3000)c = 12;
else c = s / 250;
switch (c) {
case 0:d = 0;break;
case 1:d = 2;break;
case 2:
case 3:d = 5;break;
case 4:
case 5:
case 6:
case 7:d = 8;break;
case 8:
case 9:
case 10:
case 11:d = 10;break;
case 12:d = 15;break;
}
f = p * w * s * (1 - d / 100.0);
cout << "freight=" << f << endl;
}
//3_10 求1+2+3+...+100; for| do while | while
void test3_10() {
int s = 0;
int i = 0;
/*
for (int i = 0;i <= 100;i++) {
s += i;
}
while(i<=100){
s+=i;
i++;
}
*/
do {
s += i;
i++;
} while (i <= 100);
cout << "sum=" << s << endl;
}
//3_12 求pi的近似值
void test3_12() {
int s = 1;
double n = 1, t = 1, pi = 0;
while (fabs(t) > 1e-7) {
pi = pi + t;
n = n + 2;
s = -s;
t = s / n;
}
pi = pi * 4;
cout << setiosflags(ios::fixed) << setprecision(6);
cout << "pi=" << pi << endl;
}
//3_13 求fibonacci数列前40个数
void test3_13() {
int f = 1, s = 1;
int t = f + s;
int i = 1;
while (i<=40) {
cout << "第" << i << "个数为:";
if (i < 3) {
cout << 1 << endl;
}
if (i >= 3) {
t = f + s;
f = s;
s = t;
cout << t << endl;
}
i++;
}
}
//3_14 找出100-200之间的全部素数
void test3_14() {
bool prime;
for (int i = 100;i <= 200;i++) {
prime = true;
for (int j = 2;j <= sqrt(i);j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) {
cout << "prime=" << i << endl;
}
}
}
//3_15 译密码 E=A+4
void test3_15() {
char c;
while ((c = getchar()) != '\n') {
if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
c = c + 4;
if (c <= 'Z' + 4 && c > 'Z' || c > 'z') {
c = c - 26;
}
}
cout << c;
}
}
第四章 函数与预处理
//4_1 在主函数中调用其他函数
void printstar() {
cout << "******" << endl;
}
void print_message(void) {
cout << "welcome to C++!" << endl;
}
void test4_1() {
printstar();
print_message();
printstar();
}
//4_2 调用时数据传递
int max4_2(int x, int y) {
return x > y ? x : y;
}
void test4_2() {
int a, b, c;
cout << "please enter two integer numbers: ";
cin >> a >> b;
c = max4_2(a, b);
cout << "max=" << c << endl;
}
//4_3 对被调用的函数作声明
void test4_3() {
float add(float x, float y);
float a, b, c;
cout << "pleas enter a,b ";
cin >> a >> b;
c = add(a, b);
cout << "sum=" << c << endl;
}
float add(float x, float y) {
return x + y;
}
//4_4 函数指定为内置函数
inline int max4_4(int a, int b, int c);
void test4_4() {
int i = 10, j = 20, k = 30, m;
m = max4_4(i, j, k);
cout << "max= " << m << endl;
}
inline int max4_4(int a, int b, int c) {
if (b > a) a = b;
if (c > a)a = c;
return a;
}
//4_5 函数的重载,类型不同 求3数max
void test4_5() {
int max4_5(int a, int b, int c);
double max4_5(double a, double b, double c);
long max4_5(long a, long b, long c);
int i1, i2, i3, i;
cin >> i1 >> i2 >> i3;
i = max4_5(i1, i2, i3);
cout << "i_max= " << i << endl;
double d1, d2, d3, d;
cin >> d1 >> d2 >> d3;
d = max4_5(d1, d2, d3);
cout << "d_max= " << d << endl;
long l1, l2, l3, l;
cin >> l1 >> l2 >> l3;
l = max4_5(l1, l2, l3);
cout << "l_max= " << l << endl;
}
int max4_5(int a, int b, int c) {
if (b > a) a = b;
if (c > a)a = c;
return a;
}
double max4_5(double a, double b, double c) {
if (b > a) a = b;
if (c > a)a = c;
return a;
}
long max4_5(long a, long b, long c) {
if (b > a) a = b;
if (c > a)a = c;
return a;
}
//4_6 函数的重载,参数不同
void test4_6() {
int max4_6(int a, int b, int c);
int max4_6(int a, int b);
int a, b, c,m1,m2;
cin >> a >> b >> c;
m1 = max4_6(a, b, c);
m2 = max4_6(a, b);
cout << "3_max= " << m1 << endl;
cout << "2_max=" << m2 << endl;
}
int max4_6(int a, int b, int c) {
if (b > a) a = b;
if (c > a) a = c;
return a;
}
int max4_6(int a, int b) {
return a > b ? a : b;
}
//4_7 函数模版
template<typename T> //模版声明
T max4_7(T a, T b, T c) {
if (b > a) a = b;
if (c > a)c = a;
return a;
}
void test4_7() {
int a, b, c,i;
a = 10, b = 20, c = 15;
i = max4_7(a, b, c);
cout << "i_max= " << i << endl;
double A, B, C, d;
A = 3.7, B = 5.6, C = 1.2;
d = max4_7(A, B, C);
cout << "d_max= " << d << endl;
}
//4_8 有默认参数的函数 求max
void test4_8() {
int max4_8(int a, int b, int c = 0);
int a, b, c;
cin >> a >> b >> c;
cout << "max(a,b,c)= " << max4_8(a, b, c) << endl;
}
int max4_8(int a, int b, int c) {
if (b > a) a = b;
if (c > a) a = c;
return a;
}
//4_9 函数的嵌套调用 用弦截法求方程f(x)=x^3-5x^2+16x-80=0
double f(double);
double xpoint(double, double);
double root(double, double);
void test4_9() {
double x1, x2, f1, f2, x;
do {
cout << "input x1,x2: ";
cin >> x1 >> x2;
f1 = f(x1);
f2 = f(x2);
} while (f1 * f2 >= 0);
x = root(x1, x2);
cout << setiosflags(ios::fixed) << setprecision(7);
cout << "A roof of equation is " << x << endl;
}
double f(double x) {
double y;
y = x * x * x - 5 * x * x + 16 * x - 80;
return y;
}
double xpoint(double x1, double x2) {
double y;
y = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
return y;
}
double root(double x1, double x2) {
double x, y, y1;
y1 = f(x1);
do {
x = xpoint(x1, x2);
y = f(x);
if (y * y1 > 0) {
x1 = x;
}
else {
x2 = x;
}
} while (fabs(y) >= 0.00001);
return x;
}
/* 4_10 递归
有5个人坐在一起,问第5个人多少岁?他说
比第4个人大两岁。问第4个人岁数, 他说比第3个
人大两岁。问第3个人,又说比第2个人大两岁。问
第2个人,说比第1个人大两岁。最后问第1个人,
他说是10岁。请问第5个人多大 ?*/
int age(int n) {
int c;
if (n == 1) c = 10;
else c = age(n - 1) + 2;
return c;
}
void test4_10() {
cout << age(5) << endl;
}
//4_11 递归 求n!;
int fac(int n) {
int s;
if (n == 1) {
s = 1;
}
if (n > 1) {
s = fac(n - 1) * n;
}
return s;
}
void test4_11() {
cout << fac(5) << endl;
}
//4_12 静态局部变量的值
int f(int a) {
int b = 0;
static int c = 3;
b = b + 1;
c = c + 1;
return a + b + c;
}
void test4_12() {
int a = 2;
for (int i = 0;i < 3;i++) {
cout << f(a) << endl;
}
}
//4_13 静态局部变量 输出1~5的阶乘值
void test4_13() {
int fac4_13(int a);
for (int i = 1;i <= 5;i++) {
cout << i << "!=" << fac(i) << endl;
}
}
int fac4_13(int a) {
static int f = 1;
f = f * a;
return f;
}
//4_14 寄存器register 改写阶乘
int fac4_14(int a) {
register int i,f;
f = 1;
for (i = 1;i <= a;i++) {
f *= i;
}
return f;
}
//4_15 用extern对外部变量作提前引用声明,扩展程序文件的作用域
void test4_15() {
int max4_15(int, int);
extern int a, b; //变量声明,不是定义 可以再后面定义变量的值,提前使用
cout << max4_15(a, b) << endl;
}
int a = 15, b = -7;
int max4_15(int x, int y) {
return x > y ? x : y;
}
//4_16 外部函数 求max
//file1.cpp
void test4_16() {
extern int max4_16(int x, int y);
int a, b;
cin >> a >> b;
cout << max4_16(a, b) << endl;
}
//file2.cpp
int max4_16(int x, int y) {
return x > y ? x : y;
}
//4_17 条件编译命令
#define RUN //注释查看不同
void test4_17() {
int x = 1, y = 2, z = 3;
#ifndef RUN
cout << "x=" << x << ",y=" << y << ",z=" << z;
#endif // !RUN
cout << "x*y*z=" << x * y * z << endl;
}
第五章 数组
//5_1 数组元素的引用
void test5_1() {
int i, a[10];
for (i = 0;i <= 9;i++) {
a[i] = i;
}
for (i = 9;i >= 0;i--) {
cout << a[i] << endl;
}
}
//5_2 数组 求fibonacci问题
void test5_2() {
int a[20] = { 1,1 };
for (int i = 2;i < 20;i++) {
a[i] = a[i - 1] + a[i - 2];
}
for (int i = 0;i < 20;i++) {
cout << a[i] << setw(8);
}
}
//5_3 数组 冒泡排序
void test5_3() {
int a[10] = {6,3,2,8,4,7,6,4,8,9};
int i, j, t;
for (i = 0;i < 10;i++) {
for (int j = 0;j < 10 - i - 1;j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
for (int i = 0;i < 10;i++) {
cout << a[i] << " ";
}
cout << endl;
}
//5_4 二维数组 行列互换(转置)
void test5_4() {
int a[2][3] = { {1,2,3},{4,5,6} };
int b[3][2] = {};
for (int i = 0;i < 3;i++) {
for (int j = 0;j < 2;j++) {
b[i][j] = a[j][i];
}
}
for (int i = 0;i < 3;i++) {
for (int j = 0;j < 2;j++) {
cout << b[i][j] << " ";
}
cout << endl;
}
}
//5_5 3*4矩阵,求max
void test5_5() {
int a[3][4]= { {5,12,23,56},{19,28,37,46},{-12,-34,6,8} };
int max = a[0][0];
int row=0,col=0;
for (int i = 0;i < 3;i++) {
for (int j = 0;j < 4;j++) {
if (max < a[i][j]) {
max = a[i][j];
row = i;
col = j;
}
}
}
cout << "max=" << max << endl;
cout << "row = " << row << " " << "col=" << col << endl;
}
//5_6 5_5的基础下编写max_value函数
void test5_6() {
int max_value(int, int);
int a[3][4] = { {5,12,23,56},{19,28,37,46},{-12,-34,6,8} };
int max = a[0][0];
int row = 0, col = 0;
for (int i = 0;i < 3;i++) {
for (int j = 0;j < 4;j++) {
max = max_value(a[i][j], max);
if (max == a[i][j]) {
row = i;
col = j;
}
}
}
cout << "max=" << max << endl;
cout << "row = " << row << " " << "col=" << col << endl;
}
int max_value(int x, int y) {
return x > y ? x : y;
}
//5_7 数组 选择排序
void test5_7() {
void select_sort(int* array, int n);
int i;
int a[10] = { 6,3,2,8,4,7,6,4,8,9 };
select_sort(a, 10);
for (int i = 0;i < 10;i++) {
cout << a[i] << " ";
}
cout << endl;
}
void select_sort(int* array, int n) {
int i, j, k, t;
for (i = 0;i < n - 1;i++) {
k = i;
for (j = i + 1;j < n;j++) {
if (array[j] < array[k]) {
k = j;
}
}
t = array[k];
array[k] = array[i];
array[i] = t;
}
}
//5_9 字符数组 输出钻石图形
void test5_9() {
char diamond[][5] = { {' ',' ','*'},{' ','*',' ','*'},{'*',' ',' ',' ','*'},{' ','*',' ','*'},{' ',' ','*'} };
for (int i = 0;i < 5;i++) {
for (int j = 0;j < 5;j++) {
cout << diamond[i][j];
}
cout << endl;
}
}
//5_10 字符数组 求3个字符串的最大值
void test5_10() {
void max_string(char str[][30], int n);
int i;
char country_name[3][30];
for (i = 0;i < 3;i++) {
cin >> country_name[i];
}
max_string(country_name, 3);
}
void max_string(char str[][30], int n) {
int i;
char string[30];
strcpy_s(string, str[0]);
for (i = 0;i < n;i++) {
if (strcmp(str[i], string) > 0) {
strcpy_s(string, str[i]);
}
}
cout << "the largest string is:" << string << endl;
}
//5_11 string 字符串运算,输入3个字符串,将字母由小到大的顺序输出。
void test5_11() {
string string1, string2, string3, temp;
cout << "please input 3 strings:" << endl;
cin >> string1 >> string2 >> string3;
if (string2 > string3) {
temp = string2;
string2 = string3;
string3 = temp;
}
if (string1 < string2) {
cout << string1 << " " << string2 << " " << string3 << endl;
}else if (string1 <= string3) {
cout << string2 << " " << string1 << " " << string3 << endl;
}
else if (string1 > string3) {
cout << string2 << " " << string3 << " " << string1 << endl;
}
}
/*
例5.12 -一个班有n个学生,需要把每个学生的简单
材料(姓名和学号)输入计算机保存。然后可以通过
输入某-学生的姓名查找其有关资料。当输入-一个
姓名后,
程序就查找该班中有无此学生,如果有,
则输出他的姓名和学号,如果查不到,则输出“本
班无此人”。
*/
int n;
string name[50], num[50];
void test5_12() {
void input_data();
void search(string find_name);
string find_name;
cout << "please input number of this class:";
cin >> n;
input_data();
cout << "please input name you want find:";
cin >> find_name;
search(find_name);
}
void input_data() {
for (int i = 0;i < n;i++) {
cout << "input name and No.of student" << i + 1 << ":";
cin >> name[i] >> num[i];
}
}
void search(string find_name) {
int i;
bool flag = false;
for (i = 0;i < n;i++) {
if (name[i] == find_name) {
cout << name[i] << " has been found,his number is" << num[i] << endl;
flag = true;
break;
}
}
if (flag == false)
cout << "can't find this name";
}
第六章 指针
//指针数组 数组指针 https://www.jianshu.com/p/c9a46f45610a
//6_1 通过指针变量访问整型变量
void test6_1() {
int a, b;
int* p_1, * p_2;
a = 100, b = 10;
p_1 = &a;p_2 = &b;
cout << a << " " << b << endl;
cout << *p_1 << " " << *p_2 << endl;
}
//6_2 指针变量 输入a和b,2个整数,按大到小的顺序输出a和b
void test6_2() {
int a, b;
cin >> a >> b;
int* p_1, * p_2,*p;
p_1 = &a;p_2 = &b;
cout << *p_1 << " " << *p_2 << endl;
if (a < b) {
p = p_1;
p_1 = p_2;
p_2 = p;
}
cout << *p_1 << " " << *p_2 << endl;
}
//6_3 参数为指针类型 同例6_2
void test6_3() {
void swap(int* p1, int* p2);
int* p1, * p2, a, b;
cin >> a >> b;
p1 = &a;
p2 = &b;
cout << p1 << endl;
if (a < b)
swap(p1, p2);
cout << "max=" << *p1 << " min=" << *p2 << endl;
cout << p1 << endl;
}
void swap(int *p1,int *p2) {
int t;
t = *p1;
*p1 = *p2;
*p2 = t;
}
//6_4 输入a,b,c 3个整数,按由大到小的顺序输出
void test6_4() {
void exchange(int*, int*, int*);
int a, b, c, * p1, * p2, * p3;
cin >> a >> b >> c;
p1 = &a;p2 = &b;p3 = &c;
exchange(p1, p2, p3);
cout << a << " " << b << " " << c << endl;
}
void exchange(int* p1, int* p2, int* p3) {
if (*p1 < *p2) swap(p1, p2);
if (*p1 < *p3) swap(p1, p3);
if (*p2 < *p3) swap(p2, p3);
}
//6_5 指针与数组 输出数组中的全部元素
void test6_5() {
int a[10] = {7,8,3,4,2,9,8,2,3,10};
int i;
for (i = 0;i < 10;i++) {
cout << *(a + i) << " ";
}
cout << endl;
int* p;
p = a;
for (p;p < a + 10;p++) {
cout << *p << " ";
}
cout << endl;
}
//6_6 指针 将10个整数按由小到大的顺序排列(选择排序)
void test6_6() {
void select_sort6_6(int* p, int n);
int a[10] = {7,8,3,4,6,2,8,7,4,6}, i;
select_sort6_6(a, 10);
for (i = 0;i < 10;i++) {
cout << a[i] << " ";
}
cout << endl;
}
void select_sort6_6(int* p, int n) {
int i, j, k, t;
for (int i = 0;i < n-1;i++) {
k = i;
for (int j = i + 1;j < n;j++) {
if (*(p + j) < *(p + k))
k = j;
}
t = *(p + i);
*(p + i) = *(p + k);
*(p + k) = t;
}
}
//6_7 指针多维数组 输出二维数组各元素的值
void test6_7() {
int a[3][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
int* p;
for (p = a[0];p < a[0] + 12;p++) {
cout << *p << " ";
}
cout << endl;
cout <<a<<" "<< *a << " "<<a[0]<<endl;
}
//6_8 指针多维数组 输出二维数组任一行任一列元素的值
void test6_8() {
int a[3][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
int(*p)[4], i, j;
p = a;
cin >> i >> j;
cout << *(*(p + i) + j) << endl;
}
//6_9 指向数组的指针作函数参数 输出数组
void test6_9() {
void output(int(*p)[4]);
int a[3][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
output(a);
}
void output(int(*p)[4]) {
for (int i = 0;i < 3;i++) {
for (int j = 0;j < 4;j++) {
cout<<*(*(p+i)+j)<<" ";
}
cout << endl;
}
}
//6_10 字符串与指针 用字符数组存放一个字符串
void test6_10() {
char str[] = "i love china";
cout << str << endl;
}
//6_11 字符串与指针 用字符变量存放一个字符串
void test6_11() {
string str = "i love china";
cout << str << endl;
}
//6_12 字符串与指针 用字符指针指向一个字符串
void test6_12() {
const char* str = "i love china";
cout << str << endl;
}
//6_13 字符串与指针 将字符串str1复制为字符串str2
void test6_13() {
char str1[] = "i love china!",str2[20], * p1, * p2;
p1 = str1;
p2 = str2;
while (*p1 != '\0') {
*p2 = *p1;
p1++;
p2++;
}
*p2 = '\0';
p1 = str1;
p2 = str2;
cout << "str1=" << p1 << endl;
cout << "str2=" << p2 << endl;
}
//6_14 用函数指针变量调用函数
void test6_14() {
int max6_14(int,int);
int(*p)(int, int);
int a, b, m;
cin >> a >> b;
p = max6_14; //p指向max6_14函数
m = p(a, b);
cout << "max=" << m << endl;
}
int max6_14(int a,int b) {
return a > b ? a : b;
}
//6_15 指针数组 若干字符串按字母顺序(由小到大)输出
void test6_15() {
void sort(const char* name[], int n);
void print(const char* name[], int n);
const char* name[] = { "basic","fortran","c++","pascal","cobol" };
int n = 5;
sort(name, n);
print(name, n);
}
void sort(const char* name[], int n) {
const char* temp;
int i, j, k;
for (i = 0;i < n - 1;i++) {
for (j = 0;j < n - 1 - i;j++) {
if (strcmp(name[j], name[j + 1]) > 0) {
temp = name[j];
name[j] = name[j + 1];
name[j + 1] = temp;
}
}
}
}
void print(const char* name[], int n) {
for (int i = 0;i < n;i++) {
cout << *(name+i) << " "<<&name[i]<< endl;
}
}
//6_16 指向指针的指针
void test6_16() {
void print(const char* name[], int n);
const char* name[] = { "basic","fortran","c++","pascal","cobol" };
const char** p;
p = name + 2;
cout << *p << endl;
cout << **p << endl;
}
//6_17 引用 引用和变量的关系
void test6_17() {
int a = 10;
int& b = a;
a = a * a;
cout << a << setw(6) << b << endl;
b = b / 5;
cout << b << setw(6) << a << endl;
}
//6_19 值互换 传递变量的指针
void test6_19() {
void swap6_19(int *a,int *b);
int a = 3, b = 4;
cout << a <<" "<< b << endl;
swap6_19(&a, &b);
cout << a <<" "<< b << endl;
}
void swap6_19(int* a, int* b) {
int t;
t = *a;
*a = *b;
*b = t;
}
//6_20 值互换 传送变量的别名
void test6_20() {
void swap6_19(int& a, int& b);
int a = 3, b = 4;
cout << a << " " << b << endl;
swap6_19(a, b);
cout << a << " " << b << endl;
}
void swap6_19(int& a, int& b) {
int temp;
temp = a;
a = b;
b = temp;
}
//6_21 对3个变量按由小到大的顺序排序
void test6_21() {
void sort6_21(int&, int&, int&);
int a, b, c;
int a1, b1, c1;
cout << "please input 3 integers:";
cin >> a >> b >> c;
a1 = a;b1 = b;c1 = c;
sort6_21(a1, b1, c1);
cout << "sorted order is" << a1 << " " << b1 << " " << c1 << endl;
}
void sort6_21(int& a, int& b, int& c) {
int t;
if (a > b) {
t = a;
a = b;
b = t;
}
if (a > c) {
t = a;
a = c;
c = t;
}
if (b > c) {
t = b;
b = c;
c = t;
}
}
第七章 自定义数据类型
//7_1 引用结构体变量中的成员
struct Date {
int month;
int day;
int year;
};
struct Student {
int num;
char name[20];
char sex;
Date birthday;
float score;
}student1, student2 = {10002,"Doto",'M',5,23,1982,99};
void test7_1() {
student1 = student2;
cout << student1.num << endl;
cout << student1.name << endl;
cout << student1.sex << endl;
cout << student1.score << endl;
cout << student1.birthday.year << "/" << student1.birthday.month << "/" << student1.birthday.day << endl;
}
//7_2 结构体数组
/*
对候选人得票的统计程序。设有3个候选人,
最终只能有1人当选为领导。今有10个人参加投
票,从键盘先后输入这10个人所投的候选人的名
字,要求最后输出这3个候选人的得票结果。
可以定义一个候选人结构体数组,包括3个元素,
在每个元素中存放有关的数据。
*/
struct Person {
char name[20];
int count;
};
void test7_2() {
Person leader[3] = { {"Doto",0},{"Mui",0},{"Salah",0} };
int n;
char name[3][10] = { {"Doto"},{"Mui"},{"Salah"} };
cout << "0:doto 1:Mui 2:Salah" << endl;
for (int i = 0;i < 10;i++) {
cin >> n;
for (int j = 0;j < 3;j++) {
if (strcmp(name[n], leader[j].name)==0) {
leader[j].count++;
}
}
}
for (int i = 0;i < 3;i++) {
cout << leader[i].name << " " << leader[i].count << endl;
}
}
//7_3 指向结构体变量的指针 指向结构体变量的指针的应用
struct Stu {
int num;
string name;
char sex;
float score;
};
void test7_3() {
Stu student = {1001,"Doto",'M',99};
Stu* p = &student;
cout << (*p).name << " " << (*p).num <<" "<< (*p).score << " " << (*p).sex << endl;
cout << p->name << " " << p->num << endl;
}
//7_4 静态链表 next
struct Stu7_4 {
long num;
float score;
Stu7_4* next;
};
void test7_4() {
Stu7_4 a, b, c, * head, * p;
a.num = 31001;a.score = 89.5;
b.num = 31003;b.score = 90;
c.num = 31007;c.score = 85;
head = &a;
a.next = &b;
b.next = &c;
c.next = NULL;
p = head;
do {
cout << p->num << " " << p->score << endl;
p = p->next;
} while (p != NULL);
}
//7_5 结构体变量作为函数参数 指向结构体变量的指针作实参 结构体变量的引用作为函数参数
/*
例7.5有-一个结构体变量stu,
内含学生学号、姓名
和3门课的成绩。要求在main函数中为各成员赋
值,在另一函数print中将它们的值输出。
*/
struct Stu7_5 {
int num;
char name[20];
float score[3];
};
void test7_5() {
void print(Stu7_5);
void print(Stu7_5*);
void print2(Stu7_5&);
//结构体变量作为函数参数
Stu7_5 stu = { 1001,"Doto",{89,90,91} };
print(stu);
//指向结构体变量的指针作实参
Stu7_5* p = &stu;
print(p);
//结构体变量的引用作为函数参数
print2(stu);
}
//结构体变量作为函数参数
void print(Stu7_5 stu) {
cout << stu.name << " " << stu.num << " " << stu.score[0] << " " << stu.score[1] << " " << stu.score[2] << endl;
}
//指向结构体变量的指针作实参
void print(Stu7_5 *p) {
cout << p->name << " " << p->num << " " << p->score[0] << " " << p->score[1] << " " << p->score[2] << endl;
}
//结构体变量的引用作为函数参数
void print2(Stu7_5 &stu) {
cout << stu.name << " " << stu.num << " " << stu.score[0] << " " << stu.score[1] << " " << stu.score[2] << endl;
}
//7_6 动态分配和插销内存
struct Stu7_6 {
string name;
int num;
char sex;
};
void test7_6() {
Stu7_6* p;
p = new Stu7_6;
p->name = "Doto";
p->num = 1001;
p->sex = 'M';
cout << p->name << " " << p->num << " " << p->sex << endl;
delete p;
}
//7_7 共用体 一个表格存入学生和老师的数据 根据job判断是学生还老师第5列学生是class,老师是position
struct Person7_7 {
int num;
char name[10];
char sex;
char job;
union p {
int grade;
char position[10];
}category;
}person[2];
void test7_7() {
int i;
for (i = 0;i < 2;i++) {
cin >> person[i].num >> person[i].name >> person[i].sex >> person[i].job;
if (person[i].job == 's')
cin >> person[i].category.grade;
else if (person[i].job == 't')
cin >> person[i].category.position;
}
cout << endl << "No. name sex job grade/position" << endl;
for (i = 0;i < 2;i++) {
if (person[i].job == 's') {
cout << person[i].num << person[i].name << person[i].sex << person[i].job << person[i].category.grade;
}
else {
cout << person[i].num << person[i].name << person[i].sex << person[i].job << person[i].category.position;
}
}
}
//7_8 枚举类型
/*
口袋中有红、黄、蓝、白、黑5种颜色的球若
千个。每次从口袋中任意取出3个球,问得到3种不
同颜色的球的可能取法,输出每种排列的情况。
*/
void test7_8() {
enum color{red,yellow,blue,white,black};
color pri;
int n = 0;
for (int i = red;i <= black;i++) {
for (int j = red;j <= black;j++) {
if (i != j) {
for(int k=red;k<=black;k++)
if ((k != i) && (k != j)) { //当3个球均不相同时
n = n + 1;
for (int loop = 0;loop < 3;loop++) { //对3个球做处理
switch (loop) {
case 0:pri = color(i);break;
case 1:pri = color(j);break;
case 2:pri = color(k);break;
default:break;
}
switch (pri) {
case red:cout << setw(8) << "red";break;
case yellow:cout << setw(8) << "yellow";break;
case blue:cout << setw(8) << "blue";break;
case white:cout << setw(8) << "white";break;
case black:cout << setw(8) << "black";break;
default:break;
}
}
cout << endl;
}
}
}
}
cout << "n=" << n << endl;
}
第八章 类和对象
//8_1 类和对象 举例1
class Time {
public:
int hour;
int minute;
int sec;
void set_time();
void show_time();
};
void test8_1() {
Time t1;
cin >> t1.hour;
cin >> t1.minute;
cin >> t1.sec;
cout << t1.hour << ":" << t1.minute << ":" << t1.sec << endl;
}
//8_2 应用多个对象的成员
void test8_2(){
void set_time(Time&, int hour = 0, int minute = 0, int sec = 0);
void show_time(Time);
Time t1;
Time t2;
set_time(t1);
set_time(t2,13,20,99);
show_time(t1);
show_time(t2);
}
void set_time(Time& t, int hour, int minute, int sec) {
t.hour = hour;
t.minute = minute;
t.sec = sec;
}
void show_time(Time t) {
cout << t.hour << ":" << t.minute << ":" << t.sec << endl;
}
//8_3 将8_2改用含成员函数的类处理
void test8_3() {
Time t;
t.set_time();
t.show_time();
}
void Time::set_time() {
cin >> hour >> minute >> sec;
}
void Time::show_time() {
cout << hour << ":" << minute << ":" << sec << endl;
}
//8_4 类 找出一个整型数组中的元素的最大值
class Array_max {
private:
int a[5];
int max;
public:
void set_value();
void max_value();
void show_value();
};
void Array_max::set_value() {
for (int i = 0;i < 5;i++) {
cin >> a[i];
}
}
void Array_max::max_value() {
max = a[0];
for (int i = 0;i < 5;i++) {
if (max < a[i]) {
max = a[i];
}
}
}
void Array_max::show_value() {
cout << "max=" << max << endl;
}
void test8_4() {
Array_max arrmax;
arrmax.set_value();
arrmax.max_value();
arrmax.show_value();
}
第九章 关于类和对象的进一步讨论
//9_1 构造成员函数 定义构造成员函数
class Time9_1 {
private:
int hour;
int minute;
int sec;
public:
Time9_1() {
hour = 0;
minute = 0;
sec = 0;
}
void set_time();
void show_time();
};
/*也可以
Time9_1::Time9_1() {
hour = 0;
minute = 0;
sec = 0;
}
*/
void Time9_1::set_time() {
cin >> hour >> minute >> sec;
}
void Time9_1::show_time() {
cout << hour << ":" << minute << ":" << sec << endl;
}
void test9_1() {
Time9_1 t1;
t1.show_time();
t1.set_time();
t1.show_time();
}
//9_2 带参数的构造函数 有2个长方柱,有长宽高,求体积
class Box {
private:
int height;
int width;
int length;
public:
Box(); //构造函数的的重载
Box(int, int, int);
//Box(int h = 19, int w = 1, int l = 20);
int volume();
};
//或者:Box::Box(int h,int w,int l):height(h),width(w),length(l){}
Box::Box(int h,int w,int l) {
height = h;
width = w;
length = l;
}
int Box::volume() {
return height * width * length;
}
void test9_2() {
Box b(12, 12, 12);
cout << "volume =" << b.volume() << endl;
}
//9_3 构造函数的重载
/*
...
public:
Box(); //构造函数的的重载
Box(int, int, int);
...
Box::Box(int h,int w,int l) {
height = h;
width = w;
length = l;
}
*/
Box::Box() {
width = 10;
height = 10;
length = 10;
}
void test9_3() {
Box b1;
Box b2(12, 12, 12);
cout << "volume =" << b1.volume() << endl;
cout << "volume =" << b2.volume() << endl;
}
//9_4 使用默认参数的构造函数 改写9_3 若定义了全部是默认参数的构造函数,不能再定义重载构造函数
void test9_4(){
Box b;
cout << "volume =" << b.volume() << endl;
}
/*
class Box {
private:
int height;
int width;
int length;
public:
Box(int h = 19, int w = 1, int l = 20);
int volume();
};
Box::Box(int h,int w,int l) {
height = h;
width = w;
length = l;
}
*/
//9_5 析构函数(只有一个) 包含构造函数和析构函数的C++程序
class Stu9_5 {
private:
int num;
string name;
char sex;
public:
Stu9_5(int n, string nam, char s) {
num = n;
name = nam;
sex = s;
cout << "Constructor called 1" << endl;
}
~Stu9_5() { //定义析构函数
cout << "Destructor called. 2" << endl;
}
void display() {
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
}
};
void test9_5() {
Stu9_5 s1(1001, "Doto", 'f');
s1.display();
Stu9_5 s2(1002, "Mui", 'f');
s2.display();
}
/*结果:
Constructor called 1 s1的构造函数
num:1001
name:Doto
sex:f
Constructor called 1 s2的构造函数
num:1002
name:Mui
sex:f
Destructor called. 2 s2的析构函数
Destructor called. 2 s1的析构函数
*/
//9_6 对象数组(类)的使用方法
class Box9_6 {
private:
int height;
int width;
int length;
public:
Box9_6(int h = 10, int w = 12, int l = 14);//:height(h),width(h),length(l){}
int volume();
};
Box9_6::Box9_6(int h, int w, int l) {
height = h;
width = w;
length = l;
}
int Box9_6::volume() {
return height * width * length;
}
void test9_6() {
Box9_6 b[2] = {
{1,1,1}, //或Box9_6{1,1,1},
{2,2,2}
};
cout << "Vb0= " << b[0].volume() << endl;
cout << "Vb1= " << b[1].volume() << endl;
}
//9_7 对象指针(类)的使用方法
class Time9_7 {
public:
int hour;
int minute;
int sec;
Time9_7(int h,int m,int s) {
hour = h;
minute = m;
sec = s;
}
void get_time() {
cout << hour << ":" << minute << ":" << sec << endl;
}
};
void test9_7() {
Time9_7 t1(10, 13, 57);
int* p1 = &t1.hour; //定义指向整型数据的指针变量p1
cout<<t1.hour<<endl;
cout << *p1 << endl;
Time9_7* p2 = &t1; //定义指向Time类对象的指针变量p2
t1.get_time();
p2->get_time();
void(Time9_7:: * p3)(); //定义指向Time类公用成员函数的指针变量p3
p3 = &Time9_7::get_time;
(t1.*p3)();
}
//9_8 对象的常引用
void test9_8() {
void fun(const Time9_7&); //加const就不能改变实数的值
Time9_7 t1(10, 13, 56);
//fun(t1);
cout << t1.hour << endl;
}
void fun(Time9_7& t) {
t.hour = 18;
}
//9_9 对象的赋值 对象的复制
void test9_9() {
Box9_6 b1(11, 11, 11),b2;
b2 = b1;
cout << "V1 =" << b1.volume();
cout << "V2 =" << b2.volume();
}
/*
Box::Box(const Box& b){
height =b.height;
width=b.width;
length=b.length
}
Box box2(box1) //将box1复制给box2
*/
//9_10 引用静态数据成员
class Box9_10 {
public:
static int height;
int width;
int length;
Box9_10(int, int);
int volume();
};
Box9_10::Box9_10(int w, int l) {
width = w;
length = l;
}
int Box9_10::volume() {
return height * width * length;
}
int Box9_10::height = 10;
void test9_10() {
Box9_10 a(11, 11), b(12, 12);
cout << a.height << "<-a b->" << b.height << endl;
cout << Box9_10::height << endl; //通过类名调用静态成员
cout << a.volume() << " =Va" << endl;
cout << b.volume() << " =Vb" << endl;
}
//9_11 引用非静态成员的具体方法
class Stu9_11 {
private:
int num;
int age;
float score;
static float sum;
static int count;
public:
Stu9_11(int n, int a, float s) :num(n), age(a), score(s) {};
void total();
static float average();
};
void Stu9_11::total() {
sum += score;
count++;
}
float Stu9_11::average() {
return (sum / count);
}
float Stu9_11::sum = 0;
int Stu9_11::count = 0;
void test9_11() {
Stu9_11 s[3] = {
{1001,12,70},
{1002,13,88},
{1003,14,90}
};
int n;
cout << "please input the number of students:";
cin >> n;
for (int i = 0;i < n;i++) {
s[i].total();
}
cout << "the average socre of " << n << " students is" << Stu9_11::average() << endl; //调用静态成员函数
}
//9_12 友元函数 将普通函数声明为友元函数
class Time9_12 {
private:
int hour;
int minute;
int sec;
public:
Time9_12(int w,int h,int l) {
hour = w;
minute = h;
sec = l;
}
friend void display(Time9_12&); //声明友元函数
};
void display(Time9_12& t) { //友元函数,形参t是time类对象的引用
cout << t.hour << ":" << t.minute << ":" << t.sec << endl;
}
void test9_12() {
Time9_12 t(11, 11, 11);
display(t);
}
//9_13 友元成员函数的应用
class Date9_13; //类提前引用声明
class Time9_13 {
public:
Time9_13(int, int, int);
void display(Date9_13 &); //display是成员函数,形参是Date类对象的引用
private:
int hour;
int minute;
int sec;
};
class Date9_13 {
public:
Date9_13(int, int, int);
friend void Time9_13::display(Date9_13&);
private:
int month;
int day;
int year;
};
Time9_13::Time9_13(int h, int m, int s) {
hour = h;
minute = m;
sec = s;
}
void Time9_13::display(Date9_13& d) {
cout << d.year << "/" << d.month << "/" << d.day << endl;
cout << hour << ":" << minute << ":" << sec << endl;
}
Date9_13::Date9_13(int m, int d, int y) {
month = m;
day = d;
year = y;
}
void test9_13() {
Time9_13 t(10, 13, 55);
Date9_13 d(12, 25, 2004);
t.display(d);
}
//9_14 类模板 实现整数/浮点数/字符的比较
template <class numtype>
class Compare {
public:
Compare(numtype a, numtype b) {
x = a;y = b;
}
numtype max() {
return (x > y) ? x : y;
}
numtype min() {
return (x > y) ? y : x;
}
private:
numtype x, y;
};
/*类外定义函数
numtype Compare<numtype>::max(){
return x>y?x:y;
}
*/
void test9_14() {
Compare<int> cmp1(3, 7);
Compare<float> cmp2(2.3, 2.7);
Compare<char> cmp3('A', 'a');
cout << cmp1.max() << endl;
cout << cmp2.max() << endl;
cout << cmp3.max() << endl;
}
第十章 运算符重载
//10_1 通过函数来实现复数相加
class Complex {
private:
double real;
double imag;
public:
Complex() {
real = 0;
imag = 0;
}
Complex(double r, double i) {
real = r;
imag = i;
}
Complex complex_add(Complex c2); //声明复数相加函数
//Complex operator+(Complex c2); //10_2 声明重载运算符的函数
friend Complex operator+(Complex& c1, Complex& c2);//10_3 定义作为友元函数的重载函数
void display();
friend ostream& operator<<(ostream&, Complex&); //10_7 运算符"<<"重载为友元函数
friend istream& operator>>(istream&, Complex&); //10_8 运算符">>"重载为友元函数
operator double(); //10_9 类型转换函数
};
Complex Complex::complex_add(Complex c2) {
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
void Complex::display() {
cout << "(" << real << "," << imag << "i)" << endl;
}
void test10_1() {
Complex c1(3, 4), c2(3, 3),c3;
c3=c1.complex_add(c2);
c1.display();
c2.display();
c3.display();
}
//10_2 改写10_1 重载运算符“+”,使其能用于2个复数相加
/*
Complex Complex::operator+(Complex c2) {
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
*/
void test10_2() {
Complex c1(3, 4), c2(3, 3), c3;
c3 = c2 + c1;
c1.display();
c2.display();
c3.display();
}
//10_3 将运算符"+"重载为适用于复数加法,重载函数不作为成员函数,而放在类外,作为Complex类的友元函数。
/*
...
friend Complex operator+(Complex &c1,Complex &c2); //10_2 声明重载运算符的函数
...
*/
Complex operator+(Complex& c1, Complex& c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag); //不能用this
}
void test10_3() {
Complex c1(3, 4), c2(3, 3), c3;
c3 = c2 + c1;
c1.display();
c2.display();
c3.display();
}
//10_4 重载双目运算符 定义一个字符串类String,用来存放不定长的字符串,重载运算符==,<,>,用于字符串的比较运算
class String {
private:
const char * p;
public:
String() {
p = NULL;
}
String(const char* str);
friend bool operator>(String& s1, String& s2); //声明运算符函数为友元函数
friend bool operator<(String& s1, String& s2); //声明运算符函数为友元函数
friend bool operator==(String& s1, String& s2); //声明运算符函数为友元函数
void display();
};
String::String(const char* str) {
p = str;
}
bool operator>(String& s1, String& s2) {
if (strcmp(s1.p, s2.p) > 0)
return true;
return false;
}
bool operator<(String& s1, String& s2) {
if (strcmp(s1.p, s2.p) < 0)
return true;
return false;
}
bool operator==(String& s1, String& s2) {
if (strcmp(s1.p, s2.p) == 0)
return true;
return false;
}
void String::display() {
cout << p;
}
void test10_4() {
String string1("Hello"), string2("Book");
string1.display();
string2.display();
cout << endl;
cout << (string1 > string2) << endl;
cout << (string1 < string2) << endl;
cout << (string1 == string2) << endl;
}
//10_5 重载单目运算符 有一个Time类,包含数据成员minute(分)和sec(秒),模拟秒表60秒进一分钟
class Time {
private:
int minute;
int sec;
public:
Time() {
minute = 0;
sec = 0;
}
Time(int m, int s) :minute(m), sec(s) {} //构造重载函数
Time operator++(); //声明前置自增运算符“++”重载函数
Time operator++(int); //声明后置自增运算符“++”重载函数
void display() {
cout << minute << ":" << sec << endl;
}
};
Time Time::operator++() { //定义前置自增运算符“++”重载函数
if (++sec >= 60) {
sec -= 60;
minute++;
}
return *this;
}
Time Time::operator++(int) {
Time temp(*this);
sec++;
if (sec >= 60) {
sec -= 60;
++minute;
}
return temp;
}
void test10_5() {
Time t(0, 0);
for (int i = 0;i < 121;i++) {
++t;
}
t.display();
//(t++).display();
//(++t).display();
t++;
t.display();
++t;
t.display();
}
//10_7 重载流插入运算符“<<” 参见10_1声明
/*
friend ostream& operator<<(ostream&, Complex&); //运算符"<<"重载为友元函数
*/
ostream& operator<<(ostream& output, Complex& c) { //定义运算符"<<"重载函数
if(c.imag>=0)
output << "(" << c.real << "+" << c.imag << "i)" << endl;
else
output << "(" << c.real << "" << c.imag << "i)" << endl;
return output;
}
void test10_7() {
Complex c1(2, 4), c2(3, 6), c3;
c3 = c1 + c2;
cout << c3;
}
//10_8 重载流插入运算符“>>” 参见10_1声明
/*
friend istream& operator<<(istream&, Complex&); //运算符">>"重载为友元函数
*/
istream& operator>>(istream& input, Complex& c) { //定义运算符">>"重载函数
cout << "input real part and imaginary part complex number:";
input >> c.real >> c.imag;
return input;
}
void test10_8() {
Complex c1;
cin >> c1;
cout << c1;
}
//10_9 类型转换函数的简单例子
Complex::operator double() {
return real;
}
void test10_9() {
Complex c1(3, 4), c2(3, 3), c3;
double d;
d = 2.5 + c1;
cout << d << endl;
}
第十一章 继承和派生
//11_1 访问共有基类的成员
class Student {
private:
int num;
string name;
char sex;
public:
void get_value() {
cin >> num >> name >> sex;
}
void display() {
cout << "num:" << num << endl;
cout << "name" << name << endl;
cout << "sex" << sex << endl;
}
};
class Student1 :public Student { //以public方式声明派生类Student1
private:
int age;
string addr;
public:
void display_1() {
//cout << "num:" << num << endl;错误 引用基类私有成员
//cout << "name" << name << endl;
//cout << "sex" << sex << endl;
cout << age << endl;
cout << addr << endl;
}
};
void test11_1() {
Student1 stud;
stud.display(); //调用基类的公用成员函数
stud.display_1(); //调用派生类的公用成员函数
}
//11_2 将11_1中的公用继承方式改为用私有继承方式
class Student2 :private Student { //以私有继承方式声明派生类Student1
private:
int age;
string addr;
public:
void display_1() {
display(); //正确:调用基类的公用成员函数
cout << age << endl;
cout << addr << endl;
}
};
void test11_2() {
Student2 stud;
//stud.display(); //错误:私有基类的公用成员函数在派生类中是私有函数
stud.display_1(); //调用派生类的公用成员函数
//stud.age = 18; //错误:外界不能引用派生类的私有成员
}
//11_3 在派生类中引用保护成员
class Stu11_3 {
protected:
int num;
string name;
char sex;
public:
void get_value() {
cin >> num >> name >> sex;
}
void display() {
cout << "num:" << num << endl;
cout << "name" << name << endl;
cout << "sex" << sex << endl;
}
};
class Student3 :protected Stu11_3 {
private:
int age;
string addr;
public:
void get_value1() {
get_value();
cin >> age >> addr;
}
void display1() {
cout << "num:" << num << endl; //num、name、sex是基类中的保护成员 均合法
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
cout << "age:"<<age << endl;
cout <<"addr:" <<addr << endl;
}
};
void test11_3() {
Student3 s1;
s1.get_value1();
s1.display1();
//s1.num = 111; //错误 外界不能访问保护成员
}
//11_5 简单的派生类的构造函数
class Stu11_5 {
protected:
int num;
string name;
char sex;
public:
Stu11_5(int n,string nam, char s) {
cout << "constructor ! 1" << endl;
num = n;
name = nam;
sex = s;
}
~Stu11_5() {
cout << "deconstructor ! 1" << endl;
}
};
class Student5 :public Stu11_5 {
private:
int age;
string addr;
public:
Student5(int n, string nam, char s, int a, string ad):Stu11_5(n, nam, s) { //派生类构造函数 参数初始化列表调用基类构造函数
cout << "constructor ! 2" << endl;
age = a;
addr = ad;
}
void show() {
cout << "num:" << num << endl; //num、name、sex是基类中的保护成员 均合法
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
cout << "age:" << age << endl;
cout << "addr:" << addr << endl;
}
~Student5() { //派生类构造函数
cout << "deconstructor ! 2" << endl;
int age;
string addr;
}
};
void test11_5() {
Student5 s1(1001, "doto", 'f', 20, "haha");
Student5 s2(1002, "doto2", 'f', 21, "haha2");
s1.show();
s2.show();
}
//11_6 包含子对象的派生类的构造函数
class Stu11_6 {
protected:
int num;
string name;
public:
Stu11_6(int n, string nam) {
num = n;
name = nam;
}
void display() {
cout << "num:" << num << endl << "name:" << name << endl;
}
};
class Student6 :public Stu11_6 { //声明公用派生类Stu11_6
private:
Stu11_6 monitor; //定义子对象
int age;
string addr;
public:
Student6(int n, string nam, int n1, string nam1, int a, string ad) :Stu11_6(n, nam), monitor(n1, nam1) { //派生类构造函数
age = a;
addr = ad;
}
void show() {
cout << "This student is:" << endl;
display();
cout << "age:" << age << endl;
cout << "address" << addr << endl << endl;
}
void show_monitor() {
cout << endl << "Class monitor is:" << endl;
monitor.display(); //调用基类成员函数
}
};
void test11_6() {
Student6 s(1001,"wang-li",1002,"li-sun",19,"beijing");
s.show();
s.show_monitor();
}
//11_7 多层派生时的构造函数
class Stu11_7 {
protected:
int num;
string name;
public:
Stu11_7(int n, string nam) {
cout << "constructor ! 1" << endl;
num = n;
name = nam;
}
void display() {
cout << "num:" << num << endl;
cout << "name:" << name << endl;
}
};
class Student7 :public Stu11_7 {
private:
int age;
public:
Student7(int n, string nam, int a) :Stu11_7(n,nam) {
cout << "constructor ! 2" << endl;
age = a;
}
void show() {
display();
cout << "age:" << age << endl;
}
};
class Student7_1 :public Student7 {
private:
int score;
public:
Student7_1(int n, string nam, int a, int s) :Student7(n, nam, a) {
cout << "constructor ! 3" << endl;
score = s;
}
void show_all() {
show();
cout << "score:" << score << endl;
}
};
void test11_7() {
Student7_1 s(10010, "li", 17, 89);
s.show_all();
}
//11_8 多重继承
/*
例11.8声明一个教师(Teacher)类和一一个学生
(Student)类,用多重继承的方式声明一一个研究生
(Graduate)派生类。教师类中包括数据成员
name(姓名)、age(年龄)、 title(职称)。 学生类中包
括数据成员name1(姓名)、age(性 别)、score(成绩)。
在定义派生类对象时给出初始化的数据,然后输出
这些数据。
*/
class Tea11_8 {
protected:
string name;
int age;
string title;
public:
Tea11_8(string nam, int a, string t) {
name = nam;
age = a;
title = t;
}
void display() {
cout << "name:" << name << endl;
cout << "age" << age << endl;
cout << "title:" << title << endl;
}
};
class Stu11_8 {
protected:
string name1;
char sex;
float score;
public:
Stu11_8(string nam, char s, float sco) {
name1 = nam;
sex = s;
score = sco;
}
void display() {
cout << "name:" << name1 << endl;
cout << "sex:" << sex << endl;
cout << "score:" << score << endl;
}
};
class Graduate :public Tea11_8, public Stu11_8 { //声明多重继承的派生类
private:
float wage;
public:
Graduate(string nam, int a, char s, string t, float sco, float w) :Tea11_8(nam, a, t), Stu11_8(nam, s, sco), wage(w) {
}
void show() {
Tea11_8::display();
cout << endl;
Stu11_8::display();
cout << "wage:" << wage << endl;
}
};
void test11_8() {
Graduate g1("wang-li", 24, 'f', "assistant", 90, 1234);
g1.show();
}
//11_9 虚基类的简单应用举例(避免二义性) 在11_8的基础上添加共同基类person
class Per11_9 {
protected:
string name;
char sex;
int age;
public:
Per11_9(string nam, char s, int a) {
name = nam;
sex = s;
age = a;
}
};
class Tea11_9:virtual public Per11_9 { //声明Person为公用继承的虚基类
protected:
string title;
public:
Tea11_9(string nam, char s,int a,string t):Per11_9(nam,s,a) {
title = t;
}
};
class Stu11_9:virtual public Per11_9 {
protected:
float score;
public:
Stu11_9(string nam, char s,int a,float sco) :Per11_9(nam,s,a){ ////声明Student为公用继承的虚基类
score = sco;
}
};
class Gra11_9 :public Tea11_9, public Stu11_9 { //声明多重继承的派生类
private:
float wage;
public:
Gra11_9(string nam,char s, int a, string t, float sco, float w) :Per11_9(nam,s,a),Tea11_9(nam,s, a, t), Stu11_9(nam,a, s, sco), wage(w) {
}
void show() {
cout << "name:" << name << endl;
cout << "age:" << age << endl;
cout << "sex:" << sex << endl;
cout << "score" << score << endl;
cout << "title:" << title << endl;
cout << "wages:" << wage << endl;
}
};
void test11_9() {
Gra11_9 g1("wang-li", 'f',24, "assistant", 90, 1234);
g1.show();
}
//11_10 指向基类对象的指针指向派生类对象
void test11_10() {
Stu11_8 s1("Doto", 'm', 18);
Graduate g1("wang-li", 24, 'f', "assistant", 90, 1234);
Stu11_8* pt = &s1;
pt->display();
pt = &g1;
pt->display(); //只显示和基类相同的成员函数
}
第十二章 多态性和虚拟函数
//12_1 多态性 继承 运算符重载
/*
例12.1先建立一一个Point(点)类,包含数据成员
x,y(坐标点)。以它为基类,派生出-一个Circle(圆)
类,增加数据成员r(半径),再以Circle类为 直接基
类,派生出一个Cylinder(圆柱体)类,再增加数据
成员h(高)。要求编写程序,重载运算符“<<”和
“>>”', 使之能用于输出以上类对象。
*/
//Point 类
class Point {
protected:
float x, y;
public:
Point(float x = 0, float y = 0);
void setPoint(float, float);
float getX() const {
return x;
}
float getY() const {
return y;
}
friend ostream& operator<<(ostream&, const Point&);
};
Point::Point(float a, float b) {
x = a;
y = b;
}
void Point::setPoint(float a, float b) {
x = a;
y = b;
}
ostream& operator<<(ostream& output, const Point& p) {
output << "|" << p.x << "," << p.y << "|" << endl;
return output;
}
//Circle 类
#define Pi 3.1415926
class Circle :public Point {
protected:
float radius;
public:
Circle(float x = 0, float y = 0, float r = 0);
void setRadius(float);
float getRadius() const;
float area() const;
friend ostream& operator<<(ostream&, const Circle&);
};
Circle::Circle(float a, float b, float r) :Point(a, b), radius(r) {}
void Circle::setRadius(float r) {
radius = r;
}
float Circle::getRadius() const { return radius; }
float Circle::area()const {
return Pi * radius * radius;
}
ostream& operator<<(ostream& output, const Circle& c) {
output << "Center=|" << c.x << "," << c.y << "|,r=" << c.radius << ",area=" << c.area() << endl;
return output;
}
//Cylinder 类
class Cylinder :public Circle {
protected:
float height;
public:
Cylinder(float x = 0, float y = 0, float r = 0, float h = 0);
void setHeight(float);
float getHeight() const;
float area() const;
float volume() const;
friend ostream& operator<<(ostream&, const Cylinder&);
};
Cylinder::Cylinder(float a, float b, float r, float h) :Circle(a, b, r), height(h) {}
void Cylinder::setHeight(float h) {
height = h;
}
float Cylinder::getHeight() const{
return height;
}
float Cylinder::area() const { //表面积
return 2 * Circle::area() + 2 * Pi * radius*height;
}
float Cylinder::volume() const {
return Circle::area() * height;
}
ostream& operator<<(ostream& output, const Cylinder& cy) {
output << "Center=|" << cy.x << "," << "|,r=" << cy.radius << ",h=" << cy.height << "\narea=" << cy.area() << ",volume=" << cy.volume() << endl;
return output;
}
void test12_1() {
/*
//测试Point类
Point p(1, 2);
cout << p << endl;
p.setPoint(1.3, 3.4);
cout << p << endl;
*/
/*
//测试circle 类
Circle c(3.5, 6.4, 5.2);
cout << c << endl;
c.setRadius(8);
c.setPoint(10,10);
cout << c << endl;
*/
//测试Cylinder 类
Cylinder cy(3, 3, 3, 10);
cout << cy << endl;
cy.setHeight(20);
cy.setRadius(8);
cy.setPoint(5, 5);
Point& pRef = cy;
cout << pRef << endl;
Circle cRef = cy;
cout << cRef << endl;
}
//12_2 虚函数 基类和派生类中有同名函数
class Stu12_2 {
protected:
int num;
string name;
float score;
public:
Stu12_2(int, string, float);
virtual void display(); //虚函数加virtual和不加vitual
};
Stu12_2::Stu12_2(int n, string nam, float s) {
num = n;
name = nam;
score = s;
}
void Stu12_2::display() {
cout << "num:" << num << "\nname:" << name << "\nscore:" << score << "\n\n";
}
class Gra12_2 :public Stu12_2 {
private:
float pay;
public:
Gra12_2(int, string, float, float);
void display();
};
Gra12_2::Gra12_2(int n, string nam, float s, float p) :Stu12_2(n, nam, s) ,pay(p) {}
void Gra12_2::display() {
cout << "num:" << num << "\nname:" << name << "\nscore:" << score << "\npay:" << pay << endl;
}
void test12_2() {
Stu12_2 s1(1001, "Li", 87.5);
Gra12_2 g1(2001, "wang", 98.5, 563.5);
Stu12_2* p = &s1; //定义指向基类对象的指针变量pt
p->display();
p = &g1;
p->display(); //student类 display函数加关键字virtual,调用的就是graduate的display
}
//12_3 虚析构函数 基类中有非虚析构函数时的执行情况
class Point12_3 {
public:
Point12_3() {}
virtual ~Point12_3() { //虚析构函数
cout << "executing Point destructor" << endl;
}
};
class Circle12_3 :public Point12_3 {
private:
int radius;
public:
Circle12_3(){}
~Circle12_3() {
cout << "executing Circle destructor" << endl;
}
};
void test12_3() {
Point12_3* p = new Circle12_3;
delete p; //不改动,释放空间时只执行基类析构函数 将基类析构函数前+virtual可执行
}
//12_4 虚函数和抽象基类的应用
class Shape12_4 { //声明抽象基类shape
public:
virtual float area() const { return 0.0; } //虚函数
virtual float volume() const { return 0.0; }
virtual void shapeName() const = 0;//纯虚函数
};
class Point12_4 :public Shape12_4 {
protected:
float x, y;
public:
Point12_4(float = 0, float = 0);
void setPoint(float, float);
float getX() const { return x; }
float getY() const { return y; }
virtual void shapeName() const { cout << "Point:"; } //对虚函数进行再定义
friend ostream& operator<<(ostream&, const Point12_4&);
};
Point12_4::Point12_4(float a, float b) {
x = a;
y = b;
}
void Point12_4::setPoint(float a, float b) {
x = a;
y = b;
}
ostream& operator<<(ostream& output, const Point12_4& p) {
output << "|" << p.x << "," << p.y << "|";
return output;
}
class Circle12_4 :public Point12_4 {
protected:
float radius;
public:
Circle12_4(float x = 0, float u = 0, float r = 0);
void setRadius(float);
float getRadius() const;
virtual float area() const;
virtual void shapeName() const { cout << "Circle:"; }//对虚函数进行再定义
friend ostream& operator<<(ostream&, const Circle12_4&);
};
Circle12_4::Circle12_4(float a,float b,float r):Point12_4(a,b),radius(r){}
void Circle12_4::setRadius(float r) {
radius = r;
}
float Circle12_4::getRadius() const {
return radius;
}
float Circle12_4::area() const {
return Pi * radius * radius;
}
ostream& operator<<(ostream& output, const Circle12_4& c) {
output << "|" << c.x << "," << c.y << "|,r=" << c.radius;
return output;
}
//声明Cylinder类
class Cylinder12_4 :public Circle12_4 {
protected:
float height;
public:
Cylinder12_4(float x = 0, float y = 0, float r = 0, float h = 0);
void setHeight(float);
virtual float area() const;
virtual float volume() const;
virtual void shapeName() const {
cout << "Cylinder:";
}
friend ostream &operator<< (ostream&, const Cylinder12_4&);
};
Cylinder12_4::Cylinder12_4(float a, float b, float r, float h) :Circle12_4(a, b, r), height(h) {}
void Cylinder12_4::setHeight(float h) { height = h; }
float Cylinder12_4::area() const {
return 2 * Circle12_4::area() + 2 * Pi * radius * height;
}
float Cylinder12_4::volume() const {
return Circle12_4::area() * height;
}
ostream& operator<<(ostream& output, const Cylinder12_4& c) {
output << "|" << c.x << "," << c.y << "|,r=" << c.radius<<",h"<<c.height;
return output;
}
void test12_4() {
Point12_4 p(3.2, 4.5);
Circle12_4 c(2.4, 1.2, 5.6);
Cylinder12_4 cy(3.5, 6.4, 5.2, 10.5);
p.shapeName(); //静态关联
cout << p << endl;
c.shapeName(); //静态关联
cout << c << endl;
cy.shapeName(); //静态关联
cout << cy << endl << endl;
Shape12_4* pt; //定义基类指针
pt = &p; //指针指向Point类对象
pt->shapeName(); //动态关联
cout << p.getX() << "," << p.getY() << endl;
cout << "x=" << pt->area() << "\nvolume=" << pt->volume() << "\n\n";
pt = &c; //指针指向Circle类对象
pt->shapeName(); //动态关联
cout << c.getX() << "," << c.getY() << endl;
cout << "x=" << pt->area() << "\nvolume=" << pt->volume() << "\n\n";
pt = &cy; //指针指向Circle类对象
pt->shapeName(); //动态关联
cout << cy.getX() << "," << cy.getY() << endl;
cout << "x=" << pt->area() << "\nvolume=" << pt->volume() << "\n\n";
}
第十三章 输入输出流
//13_1 cerr输出出错信息(不经过缓存区,clog经过缓存区)
/*
例13.1有一元二次方程ax2 + bx + c = = 0,
其 - -般解为x1.2 = (-b+-b^2 - 4ac) / 2a, 但若a = 0, 或b2 - 4ac < 0时, 用此
公式出错。编程序,从键盘输入a, b, c的值,求x1和x2。 如果a = 0或b2 - 4ac < 0, 输出出错信息。
*/
void test13_1() {
float a, b, c, disc;
cout << "please input a,b,c:";
cin >> a >> b >> c;
if (a == 0) {
cerr << "a is equal to zero,error!" << endl; //将有关出错信息插入cerr流,在屏幕输出
}
else {
if ((disc = b * b - 4 * a * c) < 0) {
cerr << "disc = b*b-4*a*c<0" << endl;
}
else {
cout << "x1=" << (-b + sqrt(disc) / (2 * a));
cout << " x2=" << (-b + sqrt(disc) / (2 * a));
}
}
}
//13_2 用控制符控制输出格式
void test13_2() {
int a;
cout << "input a:";
cin >> a;
cout << "dec:" << dec << a << endl;
cout << "hex:" << hex << a << endl;
cout << "oct:" << oct << a << endl;
cout << "oct:" << setbase(8) << a << endl;
const char* pt = "China";
cout << setw(10) << pt << endl;
cout << setfill('*') << setw(10) << pt << endl; //域宽10,空白补*
double pi = 22.0 / 7.0;
cout << setiosflags(ios::scientific) << setprecision(8); //指数形式输出,8位小数
cout << "pi=" << pi << endl;
cout << "pi=" << setprecision(4) << pi << endl; //4位小数
cout << "pi=" << setiosflags(ios::fixed) << pi << endl; //改为小数形式输出
}
//13_3 用流控制成员函数输出数据
void test13_3() {
int a = 21;
cout.setf(ios::showbase); //显示基数符号(0x或0)
cout << "dec:" << a << endl;
cout.unsetf(ios::dec); //终止十进制的格式设置
cout.setf(ios::hex); //设置十六进制输出的状态
cout << "hex:" << a << endl;
cout.unsetf(ios::hex);//终止十六进制的格式设置
cout.setf(ios::oct);
cout << "oct:" << a << endl;
cout.unsetf(ios::oct);
const char* pt = "China";
cout.width(10); //指定域宽为10
cout << pt << endl;
cout.width(10);
cout.fill('*');
cout << pt << endl;
double pi = 22.0 / 7.0;
cout.setf(ios::scientific); //指定用科学计数法记数
cout << "pi=";
cout.width(14); //指定域宽14
cout << pi << endl;
cout.unsetf(ios::scientific); //终止科学计数法
cout.setf(ios::fixed);
cout.width(12); //指定域宽12
cout.setf(ios::showpos); //正数输出"+"号
cout.setf(ios::internal); //数符出现在左侧
cout.precision(6);
cout << pi << endl;
}
//13_4 (cout.put 和putchar 实现)有一字符串“Basic”,将其按相反的顺序输出
void test13_4() {
const char* a = "Basic";
for (int i = 4;i >= 0;i--) {
cout.put(*(a + i));
}
cout.put('\n');
for (int i = 4;i >= 0;i--) {
putchar(*(a + i));
}
putchar('\n');
}
//13_5 while (cin >> grade) 通过测试cin的真值,判断流对象是否处于正常状态。
void test13_5() {
float grade;
cout << "enter grade:";
while (cin >> grade) {
if (grade >= 85) cout << grade << "Good!" << endl;
if (grade < 60) cout << grade << "fail" << endl;
cout << "enter grade:";
}
cout << "the grade:" << endl;
}
//13_6 cin.get 用get函数读入字符
void test13_6() {
//没有参数
/*
char c;
cout << "enter a sentence:" << endl;
while (c = cin.get() != EOF) {
cout.put(c);
}
*/
//一个参数
/*
char c;
cout << "enter a sentence:" << endl;
while (cin.get(c)) {
cout.put(c);
}
*/
//有3个参数(字符指针/数组,字符个数,终止字符)
char ch[20];
cout << "enter a sentence:" << endl;
cin.get(ch, 10, '\n');
cout << ch << endl;
}
//13_7 getline 用成员函数getline函数读入一行字符
void test13_7() {
char ch[20];
cout << "enter a sentence:" << endl;
cin >> ch;
cout << "the string read with cin is:" << ch << endl;
cin.getline(ch, 20, '/'); //读19个字符或遇到'/'结束
cout << "The second part is:" << ch << endl;
cin.getline(ch, 20); //读19个字符或遇到'/n'结束
cout << "The third part is:" << ch << endl;
}
//13_8 cin.eof
void test13_8() {
char c;
while (!cin.eof()) { //没遇到结束符为真,继续执行
if (c = cin.get() != ' ') {
cout.put(c);
}
}
}
//13_9 cin.peek cin.putback
void test13_9() {
char c[20];
int ch;
cout << "please enter a sentence:" << endl;
cin.getline(c, 15, '/');
cout << "the first part is:" << c << endl;
ch = cin.peek(); //观看当前字符
cout << "the next character (ASCII code) is:" << ch << endl;
cin.putback(c[0]); //将'I'插入到指针所指出
cin.getline(c, 15, '/');
cout << "the second part is:" << c << endl;
}
//13_10 cin.ignore 用ignore函数跳过输入流中的字符
void test13_10() {
char ch[20];
cin.get(ch, 20, '/');
cout << "the first part is:" << ch << endl;
cin.ignore(5,'A'); //跳过5个字符,遇到a不再跳
cin.get(ch, 20, '/');
cout << "The second part is:" << ch << endl;
}
//13_11 创建文件写入
void test13_11() {
int a[10];
ofstream outfile("f1.dat", ios::out); //定义文件流对象,打开磁盘文件f1.dat
if (!outfile) { //打开失败返回0
cerr << "open error!" << endl;
exit(1);
}
cout << "enter 10 integer numbers:" << endl;
for (int i = 0;i < 10;i++) {
cin >> a[i];
outfile << a[i] << " ";
}
outfile.close();
}
//13_12 读取文件读入数据
void test13_12() {
int a[10], max, i, order;
ifstream infile("f1.dat", ios::in | ios::_Nocreate);
if (!infile) {
cerr << "open error!" << endl;
exit(1);
}
for (i = 0;i < 10;i++) {
infile >> a[i]; //读入10个整数
cout << a[i] << " ";
}
cout << endl;
//infile.close();
}
//13_13 从键盘读入 - 行字符,把其中的字母字符依次存放在磁盘文件f2.dat中。再把它从磁盘文件读入程序,将其中的小写字母改为大写字母,再存入磁盘文件f3.dat。
void save_to_file() { //读入字符,存入磁盘文件
ofstream outfile("f2.dat");
if (!outfile) {
cerr << "open f2.dat erro1!" << endl;
exit(1);
}
char c[80];
cin.getline(c, 80); //从键盘读入一行字符
for (int i = 0;c[i] != 0;i++) {
if (c[i] >= 65 && c[i] <= 90 || c[i] >= 97 && c[i] <= 122) {
outfile.put(c[i]);
cout << c[i];
}
cout << endl;
}
outfile.close();
}
void get_from_file() { //读入f2.dat字母,将小写转为大写,存入f3.dat
char ch;
ifstream infile("f2.dat", ios::in | ios::_Nocreate);
if (!infile) {
cerr << "open f2.dat error!" << endl;
exit(1);
}
ofstream outfile("f3.dat");
if (!outfile) {
cerr << "open f2.dat erro1!" << endl;
exit(1);
}
while (infile.get(ch)) { //当读取字符成功时执行下面的复合语句
if (ch >= 97 && ch <= 122) {
ch = ch - 32;
outfile.put(ch);
cout << ch;
}
else {
cout << "error" << endl;
}
cout << endl;
}
infile.close();
outfile.close();
}
void test13_13() {
save_to_file();
get_from_file();
}
//13_14 read write 读写二进制文件
struct stu13_14 {
char name[20];
int num;
int age;
char sex;
};
void test13_14() {
stu13_14 s[3] = {
{"Li",1001,18,'f'},
{"Fun",1002,19,'m'},
{'Wang',1004,17,'f'}
};
ofstream outfile("fstud.dat", ios::binary);
if (!outfile) {
cerr << "open error!" << endl;
abort(); //退出程序
}
for (int i = 0;i < 3;i++) {
outfile.write((char*)&s[i], sizeof(s[i]));
}
outfile.close();
}
//13_15 将13_14二进制形式文件读入内存,并在显示器上显示
void test13_15() {
stu13_14 s[3];
int i;
ifstream infile("fstud.dat", ios::binary);
if (!infile) {
cerr << "open error!" << endl;
abort();
}
for (i = 0;i < 3;i++) {
infile.read((char*)&s[i], sizeof(s[i]));
}
infile.close();
for (int i = 0;i < 3;i++) {
cout << "No." << i + 1 << endl;
cout << "name:" << s[i].name << endl;
cout << "num:" << s[i].num << endl;
cout << "age:" << s[i].age << endl;
cout << "sex:" << s[i].sex << endl << endl;
}
}
//13_16 随机访问二进制文件
/*
有5个学生的数据,要求:
(1) 把它们存到磁盘文件中;
(2)将磁盘文件中的第1, 3, 5个学生数据读入程
序,并显示出来;
(3) 将第3个学生的数据修改后存回磁盘文件中的
原有位置。
(4)从磁盘文件读入修改后的5个学生的数据并显
示出来。
*/
struct stu13_16 {
int num;
char name[20];
float score;
};
void test13_16() {
stu13_16 s[3]{
{1001,"Li",98,},
{1002,"Fun",99,},
{1003,'Wang',97,}
};
fstream iofile("fstud.dat", ios::in | ios::out | ios::binary);
if (!iofile) {
cerr << "open error!" << endl;
abort();
}
for (int i = 0;i < 3;i++) {
iofile.write((char*)&s[i], sizeof(s[i]));
}
stu13_16 s1[3];
for (int i = 0;i < 3;i = i + 2) {
iofile.seekg(i * sizeof(s[i]), ios::beg); //定位第0,2学生数据的开头
iofile.read((char*)&s1[i / 2], sizeof(s1[i])); //将读入的2个学生数据存放在s[1] s[2]中
cout << s1[i / 2].num << " " << s1[i / 2].name << " " << s1[i / 2].score << endl;
}
cout << endl;
s[2].num = 1012;
//strcpy(s[2].name, "wu");
s[2].score = 60;
iofile.seekp(2 * sizeof(s[0]), ios::beg); //定位第3个学生数据的开头
iofile.write((char*)&s[2], sizeof(s[2])); //更新第3个学生数据
iofile.seekg(0, ios::beg); //重新定位于文件开头
for (int i = 0;i < 3;i++) {
iofile.read((char*)&s[i], sizeof(s[i]));
cout << s1[i / 2].num << " " << s1[i / 2].name << " " << s1[i / 2].score << endl;
}
iofile.close();
}
//13_17 字符串流 将一组数据保存在字符数组中
void test13_17() {
stu13_16 s[3]{
{1001,"Li",98,},
{1002,"Fun",99,},
{1003,'Wang',97,}
};
char c[50];
ostrstream strout(c, 30); //建立输出字符串流,与数组c建立关联,缓冲区长30
for (int i = 0;i < 3;i++) {
strout << s[i].num << s[i].name << s[i].score;
}
strout << ends;
cout << "array c:" << c << endl;
}
//13_18 在 - -个字符数组c中存放了10个整数,以空格相间隔,要求将它们放到整型数组中,再按大小排序,然后再存放回字符数组c中。
void test13_18() {
char c[50] = "12 34 65 -23 -32 33 61 99 321 32";
int a[10], i, j, t;
cout << "array c:" << c << endl;
istrstream strin(c, sizeof(c));
for (i = 0;i < 10;i++) {
strin >> a[i]; //从字符数组c读入10个整数赋值给整型数组a
}
cout << "array a:";
for (i = 0;i < 10;i++) {
cout << a[i] << " ";
}
cout << endl;
for (i = 0;i < 9;i++) {
for (j = 0;j < 9 - i - 1;j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
ostrstream strout(c, sizeof(c)); //建立输出穿流对象strout并与字符数组c关联
for (i = 0;i < 10;i++)
strout << a[i] << " ";
strout << ends;
cout << "array c:" << c << endl;
}
第十四章 C++工具
//14_1 try catch throw 异常处理方法
/*
例14.1给出三角形的三边a,b,c,求三角形的面积。
只有a+b>c,b+c>a,c+a>b时才能构成三角形。设置
异常处理,对不符合三角形条件的输出警告信息,
不予计算。
*/
void test14_1() {
double triangle(double, double, double);
double a, b, c;
cin >> a >> b >> c;
try { //要检查的函数
while (a > 0 && b > 0 && c > 0) {
cout << triangle(a, b, c) << endl;
cin >> a >> b >> c;
}
}
catch (double) { //捕捉异常信息并做相应处理
cout << "a=" << a << ",b=" << b << ".c=" << c << ",that is not a triangle!" << endl;
cout << "end" << endl;
}
}
double triangle(double a, double b, double c) {
double area;
double s = (a + b + c) / 2;
if (a + b <= c || b + c <= a || c + a <= b) throw a;
area = sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
/*14_2 在函数嵌套的情况下检测异常处理。
这是一个简单的例子,用来说明在try块中有函数嵌套调用的情况下拋出异常和捕捉异常的情况。请自己先分析以下程序。
*/
void test14_2() {
void f1();
try {
f1();
}
catch (double) {
cout << "OK0!" << endl;
}
cout << "end0" << endl;
}
void f1() {
void f2();
try {
f2();
}
catch (char) {
cout << "OK1!" << endl;
}
cout << "end1" << endl;
}
void f2() {
void f3();
try {
f3();
}
catch (int) {
cout << "OK2!" << endl;
}
cout << "end2" << endl;
}
void f3() {
double a = 0;
try {
throw a;
}
catch (float) {
cout << "OK3!" << endl;
}
cout << "end3" << endl;
}
//14_3 在异常处理中处理析构函数
class Student {
private:
int num;
string name;
public:
Student(int n, string nam) {
cout << "constructor-" << n << endl;
num = n;
name = nam;
}
~Student() {
cout << "destructor-" << num << endl;
}
void get_data();
};
void Student::get_data() {
if (num == 0)throw num;
else
cout << num << " " << name << endl;
cout << "in get_data()" << endl;
}
void fun() {
Student s1(1101, "Tian");
s1.get_data();
Student s2(0, "Li");
s2.get_data();
}
void test14_3() {
cout << "main begin" << endl;
cout << "call fun()" << endl;
try {
fun();
}
catch (int n) {
cout << "num=" << n << ",error!" << endl;
}
cout << "main end" << endl;
}
//头文件cc14-5-h1.h
#include<string>
#include<cmath>
#include<iostream>
using namespace std;
namespace ns1 { //声明命名空间ns1
class Student {
private:
int num;
string name;
int age;
public:
Student(int n, string nam, int a) {
num = n;
name = nam;
age = a;
}
void get_data();
};
void Student::get_data() {
cout << num << " " << name << " " << age << endl;
}
double fun(double a, double b) {
return sqrt(a + b);
}
}
//头文件cc14-5-h2.h
#include<string>
#include<cmath>
#include<iostream>
using namespace std;
namespace ns2 { //声明命名空间ns1
class Student {
private:
int num;
string name;
char sex;
public:
Student(int n, string nam, char s) {
num = n;
name = nam;
sex = s;
}
void get_data();
};
void Student::get_data() {
cout << num << " " << name << " " << sex << endl;
}
double fun(double a, double b) {
return sqrt(a - b);
}
}
//14_5 利用命名空间来解决程序名字冲突问题
#include "cc14-5-h1.h"
#include "cc14-5-h2.h"
void test14_5() {
ns1::Student s1(101, "wang", 18); //用命名空间ns1中声明的student类定义s1
s1.get_data();
cout << ns1::fun(5, 3) << endl; //调用命名空间ns1中的fun函数
ns2::Student s2(102, "Li", 'f');
s2.get_data();
cout << ns2::fun(5, 3) << endl;
}
页面: 1 2