《计算机软件基础与c复习.ppt》由会员分享,可在线阅读,更多相关《计算机软件基础与c复习.ppt(73页珍藏版)》请在三一办公上搜索。
1、计算机软件基础与C+复习 1.A better“C”(1)引用必须初始化。int count=0;int,#define PAI 3.1415926 preprocessor,const double PAI=3.1415926;compiler,在C+中常用const变量代替宏定义:const int YES=1;/这种定义有类型信息,更安全const Type Name=Const Expression;Declares a variable to have a constant valueconst int x=123;int y=x;y=x;const int z=y;,Can be
2、used in any place where we use const expressionMust be initialized unless you make an explicit extern declaration external linkage Dont modify the value directly or indirectly Can put in header file internal linkage,void main()const int x;x=7;int*ptr=,(2)常量修饰Const限定符,C+允许初始化新分配的对象float*thingPtr=new
3、float(3.14159);char*pChar=new char(a);,C+可用new动态建立数组char*string=new char25;int size;cinsize;int*arrayInt=new intsize;,C+用delete 删除动态建立的数组delete string;delete arrayInt;,(3)运算符new和delete运算符,:是作用域分辨符,用它可以访问隐藏的全局变量。,#include double value=1.233;int main()int value=7;coutLocal value=valuenGlobal value=:va
4、lueendl;return 0;,(4)函数原型 C+与 C不同之处是声明使用原型,以保证实参和形参类型一致(编译器检查),C#include f(a,b)char*a;float b;printf(“a:%s,b:%fn”,a,b);main()f(12.3,12.3);,C+#include f(char*a,float b)cout“a:”a“,”“b”bendl;void main()f(12.3,12.3);?,在第一次出现该函数名时指定可用于内联函数默认参数的定义和匹配遵从最右原则,void f1(int a,int b=-1);void f2(int a,int b=-1,in
5、t c);,(5)函数的缺省参数,(6)函数重载(Function Overloading)C+把同一作用域内名字相同,但参数不同的函数称为重载函数。这得益于函数原型不仅给出函数名,而且指出了参数类型。为了保证编译器根据参数类型识别重载函数,必须保证重载函数的参数不同。,Play the pianoPlay basketballPlay with toyPlay the stock market,int iabs(int i);long labs(long l);double fabs(double d);,int abs(int i);long abs(long l);double abs(
6、double d);,abs(-10);abs(-1000000);double abs(3.14159);,参数类型void print(int i);void print(char*s);,参数个数int add(int il,int i2,int i3);int add(int il,int i2);,参数类型次序char*get(char*s,char ch);char*get(char ch,char*s);,仅返回值类型不同导致二义性 int print(int);double print(int);仅用const或引用使参数类型有所不同 int print(const int,2
7、.Class&Object,Class is very like Struct but limits the access rights of its members,In C+,an Object is just a variable,the purest definition is“a region of storage”.,Access specifiers,public,public means all member declarations that follow are available to everyone.,private,The private keyword means
8、 that no one can access that member except inside function members of that type.,Initialization&Cleanup,The constructor,Constructor is a special public member function without any return type Constructor can finish data members initialization and other initialization task If a class has a constructo
9、r,the compiler automatically calls that constructor at the point an object is created,before client programmers can get their hands on the object.The name of the constructor is the same as the name of the class.,How a constructor does?,class X int i;public:X();,void f()X a;/.,constructor,a.X();,clas
10、s stack private:char v100;char*p;public:stack()p=v;void push(char c)char pop();,void main()stack sta;sta.push(c);char ch=sta.pop();,default constructor,void main()stack sta();sta.push(c);char ch=sta.pop();,class stack private:char*v;char*p;int size;public:stack(int sz)v=new charsize=sz;p=v;void push
11、(char c)char pop();,void main()stack sta(100);sta.push(c);char ch=sta.pop();,void main()stack sta(100);sta.push(c);char ch=sta.pop();stack errsta;,Overloading Constructors,The constructor can have arguments to allow you to specify how an object is created,give it initialization values,and so on.,cla
12、ss stack private:char*v;char*p;int size;public:stack()size=100;v=new char100;p=v;stack(int sz)v=new charsize=sz;p=v;,void main()stack sta1;stack sta2(90);,stack(int sz=70),构造函数可以重载。例如:即可以有缺省构造函数,同时又有一个带参构造函数,这时要注意二义性。,“auto”default constructor,If you have a constructor,the compiler ensures that cons
13、truction always happens.If(and only if)there are no constructors for a class,the compiler will automatically create one for you.,class V int i;/private;/No constructorint main()V v,v210;,The destructor,In C+,cleanup is as important as initialization and is therefore guaranteed with the destructor.De
14、structor is a public member.The destructor is called automatically by the compiler when the object goes out of scope.The only evidence for a destructor call is the closing brace of the scope that surrounds the object.Destructor is named after the name of the class with a leading tilde().The destruct
15、or never has any arguments and return type.Destructor can not be overloaded.,stack()/v数组是动态分配的,/出作用域不自动释放 delete v;,this指针#include class Test public:Test(int a=0);/constructor void print()const;private:int x;Test:Test(int a)x=a;/constructorvoid Test:print()const/()around*this required cout x=x n(*th
16、is).x=(*this).x endl;int main()Test testObject(12);testObject.print();return 0;,Constructor Initializer List,Occurs only in the definition of the constructor Is a list of“constructor calls”,class X public:X():Constructor Initializer List/constructor body,Member-initializer-character,Member-initializ
17、er-character,Data-Memember-Name(initialValue),Object Members,class CEmbedded public:CEmbedded(int Parm1,int Parm2)class CContainer private:CEmbedded embedded;public:,in their declared order before their host objects are constructed,CContainer(int p1,int p2,int p3):embedded(p1,p2).,用成员初始化符表初始化其它数据类型常
18、量和引用不能在构造函数中用赋值初始化。class C private:int n;const int cInt;int 使cobject的n和cInt被初始化为0和5,数据成员rInt初始化为n的别名。,静态类成员 class CTest public:static int count;/;int CTest:count=0;/由于这种静态类成员独立于任何类对象存在,用:定义,而无需引用类实例。Static 成员和整个程序作业一样持久,但作用域仅限于此类。另外,其它访 问也是受控的(公有、私有、保护的)。,类中声明,类外定义和初始化,静态成员函数:class CTest public:stat
19、ic int getCount()/;void main()int count=CTest:getCount();/,无论CTest创建多少个实例,count将严格只存放一个拷贝。,静态成员函数只可以引用属于该类的静态数据成员或静态成员函数。#include class CTest private:static int count;public:CTest()+count;CTeat()-count;static int getCount()return count;int CTest:count=0;,类外代码用类名和作用域分辨符调用,无需引用具体实例,甚至类实例可以不存在。,因为无this
20、指针,企图访问非静态成员,编译器无法判定它所要访问的数据成员是属于哪个类的。,void main()coutCTest:getCount()“object existn”;CTest test1;CTest*ptest2=new CTest;coutCTest:getCount()“object existn”;delete ptest2;coutCTest:getCount()“object existn”;,友元友元给予别的类或非成员函数访问私有成员权利。在此类中用关键字friend声明,公有或私有区声明都行。,class X;class Y public:void f(X*);class
21、 X/Definitionprivate:int i;public:void initialize();friend void g(X*,int);/Global friend friend void Y:f(X*);/class member friend friend class Z;/Entire class is a friend friend void h();void X:initialize()i=0;void g(X*x,int i)x-i=i;void Y:f(X*x)x-i=47;,class Z private:int j;public:void initialize()
22、;void g(X*x);void Z:initialize()j=99;void Z:g(X*x)x-i+=j;void h()X x;x.i=100;/Direct data manipulationint main()X x;Z z;z.g(,/Friend.cpp,class T private:int data;friend void friend_T(T fri);public:T()data=12;void use_friend();void asYfriend();class Y friend void T:asYfriend();int i;void friend_T(T f
23、ri)fri.data=10;,void T:use_friend()T fri;this-friend_T(fri);:friend_T(fri);void T:asYfriend()Y y;y.i=10;void main()T fri,fri1;fri.friend_T(fri);friend_T(fri);Y y;y.T:asYfriend();fri1.asYfriend();,友元不是成员不能用this指针访问它。,class Person public:Person(const char*s);Person(const Person,#include Person:Person(
24、const char*s)name=new charstrlen(s)+1;strcpy(name,s);Person:Person(const Person/array delete,Copy-Constructor,When are copy ctors called?During call by valueDuring initializationDuring function return,3.Inheritance,Key technology in C+Create a new class as a type of an existing classtake the form of
25、 the existing classadd code to itwithout modifying the existing class,Person,Class relationship:Is-A,Manager,Employee,Base ClassSuperParent,Derived ClassSubChild,class BaseClass public:/public members protected:/protected members private:/private members;,Inheritance Syntax,class DerivedClass:public
26、|protected|private BaseClass;,automatically inherit all the data members and member functions in the base class,accessible,Storage of derived classs object,Space of Base-Class Data Members,Space of Additional data Members of Derived-Class,inherit,Accessibility of derived classs Members,Which members
27、 inheriting from A can be used by Bs member functions?And what about other classes?,?,Members,A classs public members are accessible by all functions in the program A classs private members are accessible only by member functions and friends of the class A classs protected members are accessible by
28、member functions and friends of the class by member functions and friends of derived classes Protected members“break”encapsulation a change to base classs protected members may require modification of all derived classes,Access protection,MembersPublic:visible to all clientsProtected:visible to clas
29、ses derived from self(and to friends)Private:visible only to self and to friends!InheritancePublic:class Derived:public Base.Protected:class Derived:protected Base.Private:class Derived:private Base.default,class employee char*name;short age;float salary;public:employee():name(0),age(0),salary(0.0)e
30、mployee(char*name1,short age1,float salary1)name=new charstrlen(name1)+1;strcpy(name,name1);age=age1;salary=salary1;void print()const cout“name:”name;cout“age:”name;cout“salary:”name;employee()delete name;,class manager:public employee;,manager m;m.print();,class employee char*name;short age;float s
31、alary;public:employee():name(0),age(0),salary(0.0)employee(char*name1,short age1,float salary1)name=new charstrlen(name1)+1;strcpy(name,name1);age=age1;salary=salary1;void print()const cout“name:”name;cout“age:”age;cout“salary:”salaryendl;employee()delete name;,class manager:public employee int leve
32、l;public:void print_level()cout“level:”levelendl;,void print_name()cout“name:”nameendl;,class employee short age;float salary;public:char*name;employee():name(0),age(0),salary(0.0)employee(char*name1,short age1,float salary1)name=new charstrlen(name1)+1;strcpy(name,name1);age=age1;salary=salary1;voi
33、d print()const cout“name:”name;cout“age:”age;cout“salary:”salaryendl;employee()delete name;,class manager:public employee int level;public:void print_level()cout“level:”levelendl;void print_name()cout“name:”nameendl;,void f()manager m;coutm.nameendl;,class employee short age;float salary;protected:c
34、har*name;public:employee():name(0),age(0),salary(0.0)employee(char*name1,short age1,float salary1)name=new charstrlen(name1)+1;strcpy(name,name1);age=age1;salary=salary1;void print()const cout“name:”name;cout“age:”age;cout“salary:”salaryendl;employee()delete name;,class manager:public employee int l
35、evel;public:manager()level=0;void print_level()cout“level:”levelendl;void print_name()cout“name:”nameendl;,void f()manager m;coutm.nameendl;,Derived classs initialization and cleanup,use constructor initializer list base-class()Manager:manager(char*name1,short age1,float salary1,int level1):employee
36、(name1,age1,salary1)level=level1;first run base-classess constructor,then derived classs constructorDestructors are called in the reverse order,/point2.h#ifndef POINT2_H#define POINT2_Hclass Point public:Point(int=0,int=0);Point();protected:/accessible by derived classes int x,y;#endif,/point2.cpp#i
37、nclude#include point2.hPoint:Point(int a,int b)x=a;y=b;cout Point constructor:x,y endl;Point:Point()cout Point destructor:x,y endl;,/circle2.h#ifndef CIRCLE2_H#define CIRCLE2_H#include point2.hclass Circle:public Point public:Circle(double r=0.0,int x=0,int y=0);Circle();private:double radius;#endif
38、,/circle2.cpp#include circle2.h“#include Circle:Circle(double r,int a,int b):Point(a,b)/call base-class constructor radius=r;/should validate cout Circle constructor:radius is radius x,y endl;Circle:Circle()cout Circle destructor:radius is radius x,y endl;,/Demonstrate when base-class and derived-cl
39、ass/constructors and destructors are called.#include#include point2.h#include circle2.hint main()/Show constructor and destructor calls for Point Point p(11,22);cout endl;Circle circle1(4.5,72,29);cout endl;Circle circle2(10,5,5);cout endl;return 0;,4.Polymorphism&virtual functions,Polymorphism,The
40、phenomenon that a symbol or name has different interpretation under different cases in a program In C+,two basic kinds of polymorphismCompile-timeRun-time,a function body,a function call,Binding,Upcasting is the act of converting from a Derived reference or pointer to a base class reference or point
41、er.,Basis of Runtime Polymorphism is:Upcasting,Pointers to base-class object can point to public derived-classs object,class B public:int i;float f;class D:public B public:char ch;int j;void f()D d;B*b=,class employee public:whoamI()cout“employee:”nameendl;class manager:public employee public:whoamI
42、()cout“manager:”nameendl;class director:public manager public:whoamI()cout“director:”nameendl;,Example:,Question:Given employee*emp20,please write a function which can display their names and class names.,empi,Solution1:Add type information in classProblem:The type information in class is controlled
43、 by programmersGood Solution:The type information in class is controlled by compiler void print_me()for(int i=0;iwhoamI();Using Virtual Function,class employee public:virtual whoamI()cout“employee:”nameendl;class manager:public employee public:whoamI()cout“manager:”nameendl;class director:public man
44、ager public:whoamI()cout“director:”nameendl;,when declaring the function in the base class,#include class A protected:int k;public:A()k=3;virtual int GetValue();int A:GetValue()return k;class B:public A public:virtual int GetValue()return k*2;void F(A*p)coutGetValue();void main()B*bp=new B;F(bp);,6P
45、ress any key to continue,During run-time,Compiler chooses the calling version look up virtual-function-table according to the actual objects type,Virtual functionA special member functionDuring compile-time,Compiler dont produce the calling version according to its static type produce virtual-functi
46、on-table(VFT),Dynamic binding,Addresses of all virtual functions of a class,A*p;/.p-g(5);/call A:g();B b;p=/call B:g();,How virtuals work in C+,manager m(“wang”,42,432.50,15);employee*e_ptr1=,Dynamic bindingBe sure to access virtual functions by pointer to base-class or reference of base-classOtherw
47、ise,compiler will use the static version,Allows user-defined types to act like built in typesJust“syntactic sugar,”another way to make a function call.To use an operator on class objects,that operator must be overloadedwith exceptions,5.Overloading Operators,Assinment operator=Address operator&Comma
48、 operator,class Complex private:double rpart;double ipart;public:Complex()rpart=ipart=0.0;Complex(double rp,double ip)rpart=rp;ipart=ip;Complex add(const Complex,Complex operator+(Complex,Complex a(10,7),b(3,5),c;c=a+b;,a.operator+(b),class Complex private:double rpart;double ipart;public:Complex()r
49、part=ipart=0.0;Complex(double rp,double ip)rpart=rp;ipart=ip;friend Complex operator+(const Complex,Complex a(10,7),b(3,5),c;c=a+b;,class Complex private:double rpart;double ipart;public:Complex()rpart=ipart=0.0;Complex(double rp,double ip)rpart=rp;ipart=ip;Complex operator+(double d)Complex temp(rp
50、art+d,ipart);return temp;Complex a,b;a=b+10.0;,a=10.0+b;,/complex.h#ifndef COMPLEX1_H#define COMPLEX1_Hclass Complex public:Complex(double=0.0,double=0.0);/constructor Complex operator+(const Complex#endif,/complex.cpp#include#include complex.hComplex:Complex(double r,double i):real(r),imaginary(i)C