VC++程序设计教程(第二版)第四章
C++面向对象程序设计(第二版) 第四章 类与对象

C++面向对象程序设计
2020年1月14日星期二
4.1.2 封装
在面向对象程序设计中抽象可以表示它 所描述事物的所有属性和操作,将抽象 得到的数据和操作相结合,形成一个有 机的整体,就叫做封装。
在C++中,是利用类(class)的形式来实 现封装的,可以通过封装,将一部分操作 或属性作为类与外部的接口,将其他成员 隐蔽起来,以达到对数据访问权限的合理 控制,使程序中不同部分之间的相互影响 减到最低限度。
4.2.1 类的声明与实现
在类的声明中只声明了函数的原形,函 数的实现可以在类外定义:
void Television::SetChannel(int ChannelNum)
{
……..
//这里为设置频道相关代码
CurrentChannel= ChannelNum;
}
void Television:: ShutDown()
C++面向对象程序设计
2020年1月14日星期二
第四章 类与对象
4.9 友元 项目设计3 面向对象程序设计中类的
应用
C++面向对象程序设计
2020年1月14日星期二
4.1 面向对象程序设计的基本特点
4.1.1 抽象 4.1.2 封装 4.1.3 继承 4.1.4 多态
C++面向对象程序设计
2020年1月14日星期二
4.1.1 抽象
抽象是面向对象程序设计的基本原则之 一,抽象与具体相对应。
一个汽车的型号就是抽象,它代表了某个 汽车的一切属性,包括最大时速,车身长 度,全车净重等。抽象就是对具体事物的 概括。
C语言程序设计教程第2版课件第4章

1. 控制语句:完成一定的控制功能。
C 有9种控制语句:
⑴if( ) ~ else ~
(条件语句)
⑵ for( ) ~
(循环语句)
⑶ while( ) ~
(循环语句)
⑷ do ~ while( ) (循环语句)
⑸ continue
4.1 C语句介绍
一、C程序结构
C程序
源程序文件1
源程序文件2 • • • • • • 源程序文件n
预处理命令 全局变量声明 函数1 • • • • • •
函数n
函数首部 函数体
局部变量声明 执行语句
二、C语句概述
C语句分类: 1.控制语句 2.函数调用语句 3.赋值语句 4.空语句 5.复合语句
main() { int x,y;
scanf(“%5d,%3d”,&x,&y); } 输入数据: 345,567
说明:
1. %后的“*”附加说明符,用来表示跳过它相应的数据。 如:scanf(“%2d ,%*3d , %2d”,&a,&b); 输入:12 , 456 , 67 结果:a=12 b=67
如:float f=123.456;
printf(“%10.2f ,%-10.2f”,f);
输出结果:
123.46,123.46
8. e格式——以指数形式输出实数。
(1) %e 如: printf(“%e”,123.456);
输出结果: 1.234560e+002
6位
3位
一般共占13列宽度
(2) % m.ne和 %–m.ne: m、n和“–”字符含义 与
c面向对象程序设计(第二版)

c面向对象程序设计(第二版)面向对象程序设计是一种以对象为基本单位的编程范式,它强调数据和方法的封装、继承和多态性。
这种设计方法使得软件更加模块化、易于扩展和维护。
《面向对象程序设计(第二版)》这本书深入探讨了面向对象编程的基本概念、原理和实践,适合初学者和有经验的程序员学习。
第一章:面向对象编程基础面向对象编程(OOP)的核心概念包括类、对象、封装、继承和多态。
类是现实世界中某些具有共同特征的事物的抽象,而对象则是类的实例。
封装是将数据和操作这些数据的方法组合在一起,隐藏内部细节,只提供必要的接口。
继承允许新类从现有类中继承属性和方法,而多态性则允许对象以多种形式表现。
第二章:类与对象类是创建对象的蓝图。
定义类时,需要指定其属性(数据成员)和方法(成员函数)。
对象是类的实例,每个对象都拥有自己的状态和行为。
书中通过实例展示了如何定义类和创建对象,以及如何通过构造函数和析构函数管理对象的生命周期。
第三章:封装封装是OOP中最重要的概念之一。
它涉及到隐藏对象的内部状态,只通过公共接口与外界交互。
封装可以提高代码的安全性和可维护性。
书中详细讨论了访问修饰符(public、private、protected)的用法,以及如何使用它们来控制类成员的访问权限。
第四章:继承继承是面向对象编程中的另一个关键概念,它允许创建新的类来扩展或修改现有类的行为。
通过继承,可以避免代码重复,提高代码的复用性。
书中介绍了单继承和多继承的概念,以及如何使用继承来实现代码的层次结构。
第五章:多态性多态性允许对象以多种形式表现。
在OOP中,多态性主要通过虚函数和抽象类来实现。
虚函数允许子类重写父类的方法,而抽象类则定义了一组接口,但具体实现由子类完成。
书中讨论了多态性的实现机制,以及如何在实际编程中应用多态性。
第六章:接口与抽象类接口定义了一组方法,但不提供实现。
抽象类是包含至少一个纯虚函数的类。
它们都用于定义对象的契约,确保对象实现特定的行为。
程序设计与C语言(第二版)章 (4)

第4章 语句及控制结构
【例 4-1】 交换两个变量的值。 解题思路: 要交换两个变量的值,必须借助第三者。设有两 个变量a和b, 当把a的数据直接赋给b时就会破坏b中的内容,而 通过第三个变量作中间过渡,就可以避免这种情况的发生,如图 4-1 所示。
第4章 语句及控制结构 图 4-1 交换两个变量值的示意图
第4章 语句及控制结构 复合语句对内部来说有多条语句,对外部来说它又是一个整
体,算是一个语句。复合语句通常用做循环语句的循环体或条件 语句的分支。例如,在上例中假设只有在a大于b时才交换它们的 值,则可以写为
if(a>b) { c=a; a=b; b=c; }
第4章 语句及控制结构
4.3 输入/输出功能语句
第4章 语句及控制结构
运行输出: a=4, b=8 a=8, b=4
其中,a=4, b=8;是逗号表达式(包含了赋值)语句。在前后两 个表达式的运算互不相关的时候,可以用逗号运算符把它们连起 来,当然也可以用分号。
第4章 语句及控制结构
4.2.3 复合语句 把多条语句用花括号括起来即构成所谓的复合语句,例如: { sum=sum+i+j; i++; j--; }
printf(″a=%-5d″, 13); 输出为: a=13 └┘ └┘ └┘
printf(″a=%3d″, 12345); 输出为: a=12345
第4章 语句及控制结构
(3) %ld格式。当输出的数据大于 32 767 时,不能再用%d格 式,这时应该用长格式%ld输出。例如:
printf(″a=%ld″, 1234567); 的输出为: a=1234567。
第4章 语句及控制结构 4.3.1 字符输入/输出功能语句
C#程序设计(第2版)4-1-3

1
创建自定义异常类
在信用卡的申请过程中,要求年龄在18到55岁之间,如果年
龄不符合要求,则抛出异常。
class LegalAgeException : System.Exception { LegalAgeException(int age) { System.Console.WriteLine("age:" + age + "不符合申请信用卡的要求!"); } }
《C#程序设计》 课程
单元4 C#进阶编程
自定义异常
目录页
PAGE OF CONTENT 01
创建自定义异常类
02
抛出自定义异常类对象
03
处理自定义异常
1
创建自定义异常类
通过继承Exception来创建自己的异常类。
class ExceptionName:Exception { //异常处理过程 }
3
处理自定义异常
自定义异常抛出后,就需要处理抛出的异常。这时,y语句块对自定义异常进行捕获处理。
3
处理自定义异常
class LegalEducationException : System.Exception { public LegalEducationException(string edu) { System.Console.WriteLine("学历"+"'"+edu+"'"+"不符合岗位要求"); } } class Program { public static void EducationCheck(string edu) { if (!edu.Equals("大专生")) { throw new LegalEducationException(edu); } }
C程序设计语言 (第二版) 课后答案第四章

Exercise 4-1Write the function strrindex(s,t) , which returns the position of the rightmost occurrence of t in s , or -1 if there is none.#include<stdio.h>#define MAXLINE 1000int getline(char line[], int max);int find_the_situaion(char t[],char s[]);int count(char v[]);void main(){char target[MAXLINE];char line[MAXLINE];while (getline(line, MAXLINE) > 0){printf("%d", find_the_situaion(line, target));}}int getline(char s[], int lim) {int c, i;i = 0;while (--lim > 0 && (c = getchar()) != EOF && c != '\n')s[i++] = c;if (c == '\n')s[i++] = c;s[i] = '\0';return i;}int find_the_situaion(char t[], char s[]){int i, j, k;int b = count(s);int c = count(t);for (i = 0; s[i] != '\0'; i++){for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++,k++);if(k==b+1){return c - i - b;}}return -1;}int count(char v[]){int a = 0;if (v[a]!='\0'){a++;}return a;}Exercise 4-2Extend atof to handle scientific notation of the form 123.45e-6 where a floating-point number may be followed by e or E and an optionally signed exponent.Exercise 4-3Given the basic framework, it's straightforward to extend the calculator. Add the modulus ( % ) operator and provisions for negative numbers.#include<stdlib.h>#include"pch.h"#include<iostream>#define MAXOP 100#define NUMBER'0'#define TRUE 1;int Getop(char[]);int getch(void);double pop(void);void push(double f);void ungetch(int c);int main(void){int type;double op2;char s[MAXOP];int flag = TRUE;while ((type = Getop(s)) != EOF){switch (type){case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\nError: Division by zero!");break;}}return EXIT_SUCCESS;}int Getop(char s[]){#define PERIOD'.'int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') ;s[1] = '\0';if (!isdigit(c) && c != PERIOD && c != '-')return c;if (c == '-'){next = getch();if (!isdigit(next) && next != PERIOD){return c;}c = next;}else{c = getch();}while (isdigit(s[++i] = c))c = getch();if (c == PERIOD)while (isdigit(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)ungetch(c);return NUMBER;}#define MAXVAL 100int sp = 0;double val[MAXVAL];double pop(void){ if (sp > 0)return val[--sp];else{printf("error: stack empty\n");return 0.0;}}void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("error: stack full, can't push %g\n", f);}#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch(int c){if (bufp >= BUFSIZE)printf("ungetch: too many characters\n");elsebuf[bufp++] = c;}Exercise 4-4Add commands to print the top element of the stack without popping, to duplicate it, and to swap the top two elements. Add a command to clear the stack.#include"pch.h"#include<stdlib.h>#include<stdio.h>#include<ctype.h>#include<math.h>#define MAXOP 100#define NUMBER 0#define TRUE 1#define FALSE 0int Getop(char s[]);void push(double val);double pop(void);void showTop(void);void duplicate(void);void swapItems(void);void clearStack();int main(void){int type;double op2;char s[MAXOP];int flag = TRUE;while ((type = Getop(s)) != EOF){switch (type){case NUMBER:push(atof(s));break;case'+':push(pop() + pop());break;case'*':push(pop() * pop());break;case'-':op2 = pop();push(pop() - op2);break;case'/':op2 = pop();if (op2)push(pop() / op2);elseprintf("\n出现错误!");break;case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\n出现错误!");break;case'?':showTop();break;case'#':duplicate();break;case'~':swapItems();break;case'!':clearStack();case'\n':printf("\n\t%.8g\n", pop());break;default:printf("\nError: 不清楚的指令 %s.\n", s);break;}}return EXIT_SUCCESS;}#define MAXVAL 100int sp = 0;double val[MAXVAL];void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("\n出现错误 %g\n", f);}double pop(void){if (sp > 0)return val[--sp];else{printf("\n出现错误\n");return 0.0;}}void showTop(void){if (sp > 0)printf("Top of stack contains: %8g\n", val[sp - 1]);elseprintf("The stack is empty!\n");}void duplicate(void){double temp = pop();push(temp);push(temp);}void swapItems(void){double item1 = pop();double item2 = pop();push(item1);push(item2);}void clearStack(void){sp = 0;}int getch(void);void unGetch(int);int Getop(char s[]){int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') ;s[1] = '\0';if (!isdigit(c) && c != '.' && c != '-')return c;if (c == '-'){next = getch();if (!isdigit(next) && next != '.'){return c;}c = next;}elsec = getch();while (isdigit(s[++i] = c))c = getch();if (c == '.')while (isdigit(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)unGetch(c);return NUMBER;}#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void unGetch(int c){if (bufp >= BUFSIZE)printf("\n出现错误\n");elsebuf[bufp++] = c;}Exercise 4-5Add access to library functions like sin , exp , and pow . See <math.h> in Appendix B, Section 4.#include<stdlib.h>#include<stdio.h>#include<ctype.h>#include<math.h>#include<string.h>#define MAXOP 100#define NUMBER 0#define IDENTIFIER 1#define TRUE 1#define FALSE 0int Getop(char s[]);void push(double val);double pop(void);void showTop(void);void duplicate(void);void swapItems(void);void clearStack();void dealWithName(char s[]);int main(void){int type;double op2;char s[MAXOP];int flag = TRUE;while ((type = Getop(s)) != EOF){switch (type){case NUMBER:push(atof(s));break;case IDENTIFIER:dealWithName(s);break;case'+':push(pop() + pop());break;case'*':push(pop() * pop());break;case'-':op2 = pop();push(pop() - op2);break;case'/':op2 = pop();if (op2)push(pop() / op2);elseprintf("\nError: division by zero!");break;case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\nError: division by zero!");break;case'?':showTop();break;case'#':duplicate();break;case'~':swapItems();break;case'!':clearStack();case'\n':printf("\n\t%.8g\n", pop());break;default:printf("\nError: unknown command %s.\n", s);break;}}return EXIT_SUCCESS;}#define MAXVAL 100int sp = 0;double val[MAXVAL];void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("\nError: stack full can't push %g\n", f);}double pop(void){if (sp > 0)return val[--sp];else{printf("\nError: stack empty\n");return 0.0;}}void showTop(void){if (sp > 0)printf("Top of stack contains: %8g\n", val[sp - 1]);elseprintf("The stack is empty!\n");}void duplicate(void){double temp = pop();push(temp);push(temp);}void swapItems(void)double item1 = pop();double item2 = pop();push(item1);push(item2);}void clearStack(void){sp = 0;}void dealWithName(char s[]){double op2;if (0 == strcmp(s, "sin"))push(sin(pop()));else if (0 == strcmp(s, "cos"))push(cos(pop()));else if (0 == strcmp(s, "exp"))push(exp(pop()));else if (!strcmp(s, "pow")){op2 = pop();push(pow(pop(), op2));}elseprintf("%s is not a supported function.\n", s); }int getch(void);void unGetch(int);int Getop(char s[]){int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') ;s[1] = '\0';if (isalpha(c)){i = 0;while (isalpha(s[i++] = c))c = getch();s[i - 1] = '\0';if (c != EOF)unGetch(c);return IDENTIFIER;}if (!isdigit(c) && c != '.' && c != '-') return c;if (c == '-'){next = getch();if (!isdigit(next) && next != '.'){return c;}c = next;}elsec = getch();while (isdigit(s[++i] = c))c = getch();if (c == '.')while (isdigit(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)unGetch(c);return NUMBER;}#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void)return (bufp > 0) ? buf[--bufp] : getchar();}void unGetch(int c){if (bufp >= BUFSIZE)printf("\nUnGetch: too many characters\n");elsebuf[bufp++] = c;}Exercise 4-6Add commands for handling variables. (It's easy to provide twenty-six variables with single-letter names.) Add a variable for the most recently printed value.#include<stdlib.h>#include<stdio.h>#include<ctype.h>#include<math.h>#include<string.h>#define MAXOP 100#define NUMBER 0/* 4-6 these are new for this exercise*/#define IDENTIFIER 1#define ENDSTRING 2/* 4-6 end of new stuff */#define TRUE 1#define FALSE 0#define MAX_ID_LEN 32#define MAXVARS 30struct varType {char name[MAX_ID_LEN];double val;};int Getop(char s[]);void push(double val);double pop(void);void showTop(void);void duplicate(void);void swapItems(void);void clearStacks(struct varType var[]);void dealWithName(char s[], struct varType var[]);void dealWithVar(char s[], struct varType var[]);int pos = 0;struct varType last;int main(void){int type;double op2;char s[MAXOP];struct varType var[MAXVARS];clearStacks(var);while ((type = Getop(s)) != EOF){switch (type){case NUMBER:push(atof(s));break;case IDENTIFIER:dealWithName(s, var);break;case'+':push(pop() + pop());break;case'*':push(pop() * pop());break;case'-':op2 = pop();push(pop() - op2);break;case'/':op2 = pop();if (op2)push(pop() / op2);elseprintf("\nError: division by zero!");break;case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\nError: division by zero!");break;case'?':showTop();break;case'#':duplicate();break;case'~':swapItems();break;case'!':clearStacks(var);break;case'\n':printf("\n\t%.8g\n", pop());break;/* 4-6 this is new for this program */case ENDSTRING:break;case'=':pop();var[pos].val = pop();last.val = var[pos].val;push(last.val);break;case'<':printf("The last variable used was: %s (value == %g)\n",, last.val);break;/* 4-6 End of new stuff */default:printf("\nError: unknown command %s.\n", s);break;}}return EXIT_SUCCESS;}#define MAXVAL 100int sp = 0;double val[MAXVAL];void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("\nError: stack full can't push %g\n", f);}double pop(void){if (sp > 0){return val[--sp];}else{printf("\nError: stack empty\n");return 0.0;}}void showTop(void){if (sp > 0)printf("Top of stack contains: %8g\n", val[sp - 1]);elseprintf("The stack is empty!\n");}void duplicate(void){double temp = pop();push(temp);push(temp);}void swapItems(void){double item1 = pop();double item2 = pop();push(item1);push(item2);}void clearStacks(struct varType var[]){int i;sp = 0;for (i = 0; i < MAXVARS; ++i){var[i].name[0] = '\0';var[i].val = 0.0;}}void dealWithName(char s[], struct varType var[]){double op2;if (!strcmp(s, "sin"))push(sin(pop()));else if (!strcmp(s, "cos"))push(cos(pop()));else if (!strcmp(s, "exp"))push(exp(pop()));else if (!strcmp(s, "pow")){op2 = pop();push(pow(pop(), op2));}else{dealWithVar(s, var);}}void dealWithVar(char s[], struct varType var[]){int i = 0;while (var[i].name[0] != '\0' && i < MAXVARS - 1) {if (!strcmp(s, var[i].name)){strcpy(, s);last.val = var[i].val;push(var[i].val);pos = i;return;}i++;}strcpy(var[i].name, s);strcpy(, s);push(var[i].val);pos = i;}int getch(void);void unGetch(int);int Getop(char s[]){int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') {;}s[1] = '\0';if (isalpha(c)){i = 0;while (isalpha(s[i++] = c)){c = getch();}s[i - 1] = '\0';if (c != EOF)unGetch(c);return IDENTIFIER;}if (!isdigit(c) && c != '.' && c != '-'){if ('=' == c && '\n' == (next = getch())){unGetch('\0');return c;}if ('\0' == c)return ENDSTRING;return c;}if (c == '-'){next = getch();if (!isdigit(next) && next != '.'){return c;}c = next;}else{c = getch();}while (isdigit(s[++i] = c)){c = getch();}if (c == '.'){while (isdigit(s[++i] = c = getch()));}s[i] = '\0';if (c != EOF)unGetch(c);return NUMBER;}#define BUFSIZE 100int buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void unGetch(int c){if (bufp >= BUFSIZE)printf("\nUnGetch: too many characters\n");elsebuf[bufp++] = c;}Exercise 4-7Write a routine ungets(s) that will push back an entire string onto the input. Should ungets know about buf and bufp , or should it just use ungetch ?#include"pch.h"#include<string.h>#include<stdio.h>#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch(int c){if (bufp >= BUFSIZE)printf("ungetch: too many characters\n");elsebuf[bufp++] = c;}void ungets(const char *s){size_t i = strlen(s);while (i > 0)ungetch(s[--i]);}int main(void){char s="Hello";int c;ungets(s);while ((c = getch()) != EOF)putchar(c);return 0;}Exercise 4-8Suppose there will never be more than one character of pushback. Modify getch and ungetch accordingly.#include<stdio.h>#include"pch.h"int buf = EOF;#define EOF -1;int getch(void){int temp;if (buf != EOF){temp = buf;buf = EOF;}else {temp = getchar();}return temp;}void ungetch(int c){if (buf != EOF)printf("ungetch: too many characters\n");elsebuf = c;}int main(void){int c;while ((c = getch()) != EOF) {if (c == '/') {putchar(c);if ((c = getch()) == '*') {ungetch('!');}}putchar(c);}return 0;}Exercise 4-9Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what their properties ought to be if an EOF is pushed back, and then implement your design.#include<stdio.h>#define BUFSIZE 100int buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch(int c){if (bufp >= BUFSIZE)printf("ungetch: too many characters \n");elsebuf[bufp++] = c;}Exercise 4-10#include<stdio.h>#include<ctype.h>#define MAXLINE 100#define NUMBER'0'int getline(char line[], int limit);int li = 0;char line[MAXLINE];int getop(char s[]){int c, i;if (line[li] == '\0')if (getline(line, MAXLINE) == 0)return EOF;elseli = 0;while ((s[0] = c = line[li++]) == ' ' || c == '\t');s[1] = '\0';if (!isdigit(c) && c != '.')return c;i = 0;if (isdigit(c))while (isdigit(s[++i] = c = line[li++]));if (c == '.')while (isdigit(s[++i] = c = line[li++]));s[i] = '\0';li--;return NUMBER;}Exercise 4-11Modify getop so that it doesn't need to use ungetch. Hint: use an internal static variable.int getop(char *s){int c;static int buf = EOF;if (buf == EOF || buf == ' ' || buf == '/t')while ((*s = c = getch()) == ' ' || c == '/t');else*s = c = buf;buf = EOF;*(s + 1) = '/0';if (!isdigit(c) && c != '.')return c; /* not a number */if (isdigit(c)) /* collect integer part */while (isdigit(*++s = c = getch()));if (c == '.') /* collect fraction part */while (isdigit(*++s = c = getch()));*++s = '/0';buf = c;return NUMBER;}Exercise 4-12Adapt the ideas of printd to write a recursive version of atoi ; that is, convert an integer into a string by calling a recursive routine. #include"pch.h"#include<iostream>#include<stdio.h>#include<stdlib.h>char *utoa(unsigned value, char *digits, int base){char *s, *p;s = "0123456789abcdefghijklmnopqrstuvwxyz";if (base == 0)base = 10;if (digits == NULL || base < 2 || base > 36)return NULL;if (value < (unsigned)base) {digits[0] = s[value];digits[1] = '\0';}else {for (p = utoa(value / ((unsigned)base), digits, base);*p;p++);utoa(value % ((unsigned)base), p, base);}return digits;}char *itoa(int value, char *digits, int base){char *d;unsigned u;d = digits;if (base == 0)base = 10;if (digits == NULL || base < 2 || base > 36)return NULL;if (value < 0) {*d++ = '-';u = -value;}elseu = value;utoa(u, d, base);return digits;}Exercise 4-13Write a recursive version of the function reverse(s) , which reverses the string s in place.#include"pch.h"#include<iostream>#include<stdio.h>#include<stdlib.h>static void swap(char *a, char *b, size_t n){while (n--) {*a ^= *b;*b ^= *a;*a ^= *b;a++;b++;}}void my_memrev(char *s, size_t n){switch (n) {case 0:case 1:break;case 2:case 3:swap(s, s + n - 1, 1);break;default:my_memrev(s, n / 2);my_memrev(s + ((n + 1) / 2), n / 2);swap(s, s + ((n + 1) / 2), n / 2);break;}}void reverse(char *s){char *p;for (p = s; *p; p++);my_memrev(s, (size_t)(p - s));}。
《VisualC教程第二版》第4章对话框

4.1从C++到Windows编程
编程特点 Windows应用程序具有这样的一些特性:消息驱动机制、图形设备接口(GDI)、基于资源的程序设计、动态链接库。 消息驱动机制 DOS程序是通过调用系统的函数来获得用户输入的,Windows程序是通过操作系统发送的消息来处理用户输入的。消息驱动的机制是Windows编程的最大特点。 WinMain函数通常要完成以下几步工作: 定义并调用API函数RegisterClass注册应用程序的窗口类。 调用相关API函数创建和显示窗口,并进行其它必要的初始化处理。其中,函数CreateWindow用来创建已注册窗口类的窗口。 创建和启动应用程序的消息循环。Windows应用程序接受各种不同的消息,包括键盘消息、鼠标以及窗口产生的各种消息。Windows系统首先将消息放入消息队列中,应用程序的消息循环就是从应用程序的消息队列中检取消息,并将消息发送相应的窗口过程函数中作进一步处理。API函数GetMessage 和DispatchMessage就是起到这样的作用。 如果接收到WM_QUIT消息,则退出应用程序。
4.1从C++到Windows编程
(4)再次选择“文 件”“新建”菜单命令,显示出“新建”对话框。单击“文件”标签,在左边的列表框中选择C++ Source File项,在右边的“文件”下的编辑框中键入Ex_HelloMsg.cpp,单击[确定]按钮。
(5) 输入下面的代码: #include <windows.h> int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox (NULL, "你好,我的Visual C++世界!", "问候", 0) ; return 0 ; }
精品文档-C语言程序设计—项目教学教程(第二版)(王德永)-第4章

项目四 火车票务管理系统 3) 结构体变量成员赋值 【例4.1.2】
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20
代码贴士
#include<stdio.h> struct TRAIN {
char *trainNum; char *date; char fromPlace[15]; char toPlace[15]; char *outTime; float price; }train1, train2; void main() { train1.trainNum="K256"; train1.date="2012-7-23"; printf("请输入出发地、目的地和票价\n"); scanf("%s%s", train1.fromPlace, train1.toPlace); scanf("%f", &train1.price); train2=train1; printf("车次=%s\n 日期=%s\n", train2.trainNum, train2.date); printf("出发地=%s\n 目的地=%s\n 票价=%f\n", train2.fromPlace, train2.toPlace, train2.price); }
项目四 火车票务管理系统 项目四 火车票务管理系统
任务1 录入火车时刻信息 任务2 查询火车时刻信息 任务3 统计火车车次
项目四 火车票务管理系统
本项目是要设计一个火车票务管理系统,实现火车时刻信 息的录入、查询和统计。录入信息包括车次、日期、起点、终 点、开车时间、到达时间、票价等,查询信息包括按照车次查 询、按终点查询、按起点查询、按终点和日期查询等,统计信 息主要包括按起点或终点统计每日的车次数。通过本项目使学 生掌握结构类型的构造及使用、文件及预处理命令。本项目使 用结构体类型来实现“火车票务管理系统”中火车时刻信息的 录入,利用文件来查询“火车票务管理系统”中列车的数据。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
继承与派生问题举例
交通工具
汽车
小 小工
卡工
旅 旅工
工 工工
轿工
面 面工
《面向对象技术与Visual C++》-第4章
4
4.2派生类 4.2派生类
派生类是特殊的基类,基类是派生类的抽象描述。 派生类是特殊的基类,基类是派生类的抽象描述。 派生类自动继承了基类的成员,但不等同于基类, 派生类自动继承了基类的成员,但不等同于基类, 否则就没有派生的必要了。 否则就没有派生的必要了。
《面向对象技术与Visual C++》-第4章 14
示例公有继承。 的另一种实现方式, 例4-2 示例公有继承。例4-1的另一种实现方式,修改主函数为: 的另一种实现方式 修改主函数为: void main() { char name[11]; cout<<"Enter a person′s name:"; cin>>name; Person p1(name,29,′m′); //基类对象 基类对象 p1.Display(); //基类对象访问基类公有成员函数 基类对象访问基类公有成员函数 cout<<"Enter a student′s name:"; cin>>name; Student s2(name,20,′m′,"03410102",80); //派生类对象 派生类对象 s2.Person::Display(); //派生类对象访问继承下来的基类的公有成员函数 派生类对象访问继承下来的基类的公有成员函数 //派生类对象访问本类的公有成员函数 与基类函数同名 派生类对象访问本类的公有成员函数(与基类函数同名 派生类对象访问本类的公有成员函数 与基类函数同名) s2.Display(); } 《面向对象技术与Visual C++》-第4章
第4章 继承与派生
本章主要内容
继承的概念 派生类 访问权限控制 派生类的构造函数和析构函数 多继承
《面向对象技术与Visual C++》-第4章
2
4.1继承的概念 4.1继承的概念
类的继承就是根据一个类创建一个新类的过程。 类的继承就是根据一个类创建一个新类的过程。 新类自动具有已有类的所有成员, 新类自动具有已有类的所有成员,并可根据需 要添加更多的成员。 要添加更多的成员。 换个角度, 换个角度,从已有类产生新类的过程就是类的 派生。 派生。 通常将用来派生新类的类称为基类 又称为父 基类, 通常将用来派生新类的类称为基类,又称为父 而将派生出来的新类称为派生类 派生类, 类,而将派生出来的新类称为派生类,又称为 子类。 子类。
//基类成员函数的声明 基类成员函数的声明 int GetAge(); char GetSex(); void Display(); private: char name[11]; char sex; protected: //保护成员 保护成员 int age; };
《面向对象技术与Visual C++》-第4章
《面向对象技术与Visual C++》-第4章
11
void main() { char name[11]; cout<<"Enter a person′s name:"; cin>>name; Person p1(name,29,′m′); //基类对象 基类对象 p1.Display(); //基类对象访问基类公有成员函数 基类对象访问基类公有成员函数 char pId[9]; cout<<"Enter a student′s name:"; cin>>name; Student s1(name,19,′f′,"03410101",95); //派生类对象访问基类成员函数 派生类对象访问基类成员函数 cout<<"name:"<<s1.GetName()<<′\t′; cout<<"id:"<<s1.GetId(pId)<<′\t′; cout<<"age:"<<s1.GetAge()<<′\t′; cout<<"sex:"<<s1.GetSex()<<′\t′; cout<<"score:"<<s1.GetScore()<<endl; }
8
Person::Person(const char *Name,int Age,char Sex) //基类构造函数的实现 基类构造函数的实现 { strcpy(name,Name); age=Age; sex=Sex; } //基类成员函数的实现 基类成员函数的实现 int Person::GetAge() void Person::Display() { return(age); {// 直 接 访 问 本 类 私 有 成 员 } cout<<"name:"<<name<<′\t′; char Person::GetSex() cout<<"age:"<<age<<′\t′; { cout<<"sex:"<<sex<<endl; return(sex); } }
派生类 基类 派生类 基类
基类的私有成员不能被继承。 基类的私有成员不能被继承。
《面向对象技术与Visual C++》-第4章 5
4.2.1派生类的定义 4.2.1派生类的定义
class <派生类名 继承方式 <基类名 派生类名>:<派生类新定义成员 派生类新定义成员> 派生类新定义成员 };
《面向对象技术与Visual C++》-第4章 16
示例私有继承。将例4-2作如下变化 方能实现数据的访问。 作如下变化, 例4-3 示例私有继承。将例 作如下变化,方能实现数据的访问。 class Student:private Person //定义私有继承的学生类 定义私有继承的学生类 { //… }; //… void Student::Display() //派生类的成员函数的实现 派生类的成员函数的实现 { cout<<"name:"<<GetName()<<′\t′; //访问变为私有的基类成员函数 访问变为私有的基类成员函数 cout<<"id:"<<id<<′\t′; //成员函数直接访问本类私有成员 成员函数直接访问本类私有成员 cout<<"age:"<<age<<′\t′; //访问基类的保护成员 现为本类私有的 访问基类的保护成员(现为本类私有的 访问基类的保护成员 现为本类私有的) cout<<"sex:"<<GetSex()<<endl; cout<<"score:"<<Score<<endl; } void main() { Student s2("wang min",20,′m′,"03410102",80); //派生类对象 派生类对象 s2.Display(); //派生类对象访问本类的公有成员函数 派生类对象访问本类的公有成员函数 s2.Person::Display(); //错误! 错误! 错误 } 《面向对象技术与Visual C++》-第4章 17
class student:public person {………….. }
《面向对象技术与Visual C++》-第4章 6
<继承方式 有三种: 继承方式>有三种 继承方式 有三种: 公有继承、私有继承和保护继承, 公有继承、私有继承和保护继承,分别用关键 表示。 字public、private和protected表示。 、 和 表示 缺省情况下为私有继承。 缺省情况下为私有继承。
15
4.3.2私有继承的访问权限控制 4.3.2私有继承的访问权限控制
基类的public和protected成员都以 和 成员都以private身份 基类的 成员都以 身份 出现在派生类中,但基类的private成员不可访问。 成员不可访问 出现在派生类中,但基类的 成员不可访问。 派生类中的成员函数 成员函数可以直接访问基类中的 派生类中的成员函数可以直接访问基类中的 public和protected成员,但不能访问基类的 成员, 和 成员 private成员。 成员。 成员 通过派生类的对象不能访问基类中的任何成员。 对象不能访问基类中的任何成员 通过派生类的对象不能访问基类中的任何成员。 私有继承之后, 私有继承之后,基类的成员再也无法在以后的派 生类中发挥作用,出于这种原因, 生类中发挥作用,出于这种原因,一般不使用私 有继承方式。 有继承方式。
示例公有继承。 例4-1 示例公有继承。
#include <iostream.h> #include <string.h> class Person //定义基类 定义基类Person 定义基类 { public: //外部接口 外部接口 Person(const char* Name, int Age,char Sex); //基类构造函数 基类构造函数 char* GetName() { return(name); }