
第1章c++概述.ppt
54页C++面向对象程序设计An Introduction to Object-Oriented Programming Using C++《C++面向对象程序设计》教学内容 第1章 C++概述 第2章 类和对象 第3章 面向对象程序设计概述 第4章 进一步学习类和对象 第5章 堆与复制构造函数 第6章 继承性:派生类 第7章 运算符重载 第8章 虚函数和多态性 第9章 模板 第10章 类库和C++的标准模板库STL 第11章 输入输出流 第12章 异常处理第一章第1章 C++概述 C++ A Better C1.1 C++起源和特点1.1.1 C++的起源1.1.2 C++的特点1.2 C++程序的结构1.2.1 C程序与C++程序比较 1.2.2 C++程序结构 1.2.3 C++程序的编辑、编译和运行C程序与C++程序比较之一main( ) { int a, b, sum; /* 定义三个整型变量 */ a = 123; b = 456;sum = a + b;printf(“sum is %d\n“, sum);} main( ) { int a, b, sum; //定义三个整型变量a = 123; b = 456;sum = a + b;cout main( ){ int i; float f;char s[80]; cout >i>>f>>s;cout #include using namespace std;int main() { char str[80];cout y) z=x;else z=y;return (z); }内联函数的调用方法与普通函数没有区别。
类中定义的内联函数Inline functionAny function defined within a class body is automatically inline,class Date{int day, month, year;public:void init_date(int dd,int mm,int yy){day=dd; month=mm; year=yy;}};Here init_date is a inline function函数调用时的时间开销1.函数调用时的时间开销:保护现场,恢复现场 2.用关键字inline说明内嵌函数编译器直接用内 嵌函数体的编译代码插入在函数调用语句处,这 一过程称为函数的嵌入扩展利用内嵌函数减少 了调用普通函数时的压栈和弹栈操作,从而提高 程序的运行速度 3.内嵌函数比带参数的宏的好处一般情况下,只有较短的函数才定义为内嵌函数 使用内嵌函数实际上是一种增加空间开销以减小 时间开销的方法为什么使用内联函数Efficiency 效率 在C程序中,可使用宏macros达到同样的目的 ,但是宏是通过预处理来处理的,不进行类型 检查,容易造成难以发现的错误。
宏macros在类的内部不能使用,宏不能作为类 的成员为什么使用内联函数(cont.)为了克服宏的上述缺陷, C++ 引入了内联函 数内联函数具有高效率,而且:进行类型检查,避免出现类型不匹配的错误 可以作为类的成员函数To retain the efficiency of the preprocessor macro, but to add the safety and class scoping of true functions, C++ has the inline function.How do inline functions work 编译器处理内联函数的过程类型检查 Type checking (To assure safety )将函数代码插入到函数调用处 then substitutes the function body for the function call 这样函数代码将占据更所得存储空间 The inline code does occupy spaceThe short,small and frequently called functions are suitable for inline functions.1.3.4 函数原型 ( function prototype ) • 什么是函数原型? • 描述函数原型的三大要素: – 函数名 – 参数类型 – 函数返回值类型 • 函数原型的例子: int translate(float x, float y, float z);int translate(float, float, float);【例1.7】 void sqr_it( ); /* function declaration */ int main( ) { int x; x=10; sqr_it(x); printf(“The square of x is %d\n“,x);return 0; } void sqr_it(int *i) { *i=(*i)*(*i); }运行时出错• 【例1.7】本例的C程序能够成功通过诸如 Turbo C这样的C编译器的检查,但会在 运行阶段发生错误。
• 该程序运行后的结构显示如下:The square of x is 10 Null pointer assignment使用函数原型执行强类型检查【例1.8】void sqr_it(int *i); //函数原型 int main( ) { int x; x=10; sqr_it(x); cout//Overload abs( ) three waysint abs(int n);long abs(long n);double abs(double n);//prototype is neccessary for C++ compiler这些都是函数原型函数重载的例子main( ){coutmain( ){int *p;p=new int; // allocate room for an integer// always make sure that allocate succeededif(!p) {coutvoid f(int // declare a reference parameter using f(i);// The address of variable i is passed.cout int int x;main() { f( )=100; // f( ) return the address of xcout< 应当避免)习 题 1 • 必做题: P20: 2, 8, 9, 10• 选作题:3, 4, 6。












