From C To C++课程设计

[b]1) 初步了解编程语言的发展的过程。面向对象的意义,C++的应用。[/b]

[b]2) 熟悉IDE.[/b]
a) 解决方案和项目
b) 程序基本结构(函数,参数,返回值)
[color=orange]练习:完成hello world[/color]

[b]3) 第一个CPP程序。[/b]
a) Include(<> ,“”)
b) 命名空间
c) 熟悉各种数据类型。
i. 基本类型Char, int, float, double, bool
ii. 说明符 long, short,signed, unsigned
[color=orange]练习:打印各种数据类型的占用内存[/color]

[b]4) 变量和作用域。[/b]
a) 全局变量、局部变量
b) 作用域(特别是for循环变量)
c) 静态变量
d) 常量
e) 变量定义和变量声明—外部变量
[color=orange]练习:用静态变量和全局变量完成两个不同函数被调用次数计数[/color]

[b]5) 熟悉各种流程语句,运算符 [/b]
a) 控制语句 if-else, while, do-while, for, switch/ break,continue
b) 运算符 赋值运算符,数学运算符,关系运算符,逻辑运算符,位运算,移位,一元运算,三元运算
[color=orange]练习:猜数游戏[/color]

[b]6) 熟悉各种复合类型[/b]
a) 枚举、联合
b) 数组
c) 指针
i. 指针+1,加了多少字节
ii. 数组和指针,作为函数参数时的数组和指针
[color=orange]练习:switch枚举类型,打印不同内容[/color]

[b]7) .h文件,语言翻译的过程,一个复杂的c程序[/b]
a) .h文件
i. 函数声明和定义
ii. Match 定义和声明
iii. 只可以写声明,不可以写定义
iv. #define
b) 语言翻译过程
i. 预编译-》编译-》链接
ii. 库文件的使用
[color=orange]练习:完成doubleContainer 框架[/color]

[b]8) 聚合数据类型struct[/b]
[color=orange]练习:实现DoubleContainer[/color]

[b]9) 数据抽象[/b]
a) 成员变量
b) 成员函数
c) 对象、实例
d) This指针
[color=orange]练习:完成DoubleContainer 数据抽象[/color]

[b]10) 嵌套类型[/b]
[color=orange]演习:用双向链表实现IntContainer[/color]

[b]11) 访问控制[/b]
a) Private, public(单例模式)
b) Friend(函数,类)
c) Class 和 struct的区别
[color=orange]练习:完成DoubleContainer访问控制[/color]

[b]12) 初始化和清除[/b]
a) 构造函数
b) 带参数的构造函数
c) 析构函数
d) New/Delete
e) 重温全局变量,局部变量和静态变量的作用域
[color=orange]练习:完成DoubleContainer(构造函数和析构函数)[/color]

[b]13) 函数重载[/b]
a) 函数重载(参数不同,返回值不同)
b) 占位符
c) 默认参数
[color=orange]练习:完成DoubleContainer(构造函数重载)[/color]

[b]14) 介绍iostream,fstream和string[/b]
a) String,构造函数, find, substring
b) Ifstream读取内容
c) Getline
d) Ofstream写文件
e) Ios::app
f) Fsteam
[color=orange]练习:创建一个Text类保存文件内容,不同的构造函数。[/color]

[b]15) 指针,引用[/b]
a) 函数值传递和指针传递
i. 返回地址时不可以是局部变量,除非是静态的
ii. 文件域,局部域,动态管理
b) 引用代替指针
[color=orange]演习:用指针和引用分别完成swap函数max函数[/color]

[b]16) 常量[/b]
a) 值定义
b) 常量指针和指针常量(赋值检查)
c) 参数和返回值中的常量
i. 内部类型和自定义类型值传递const
ii. 内部类型按值返回const
iii. 自定义类型按值返回const
iv. 内部类型和自定义类型传递和返回地址的const
v. 引用和指针的选择
d) 自定义类型常量
i. 常量定义(初始化列表,内部类型构造函数)
ii. 静态常量(初始化)
iii. 常量对象和常量成员函数(mutable)
iv. 静态成员函数
[color=orange]练习:完成DoubleContainer的常量设定[/color]

[b]17) inline函数[/b]
[color=orange]练习:完成DoubleContainer修改成内联函数[/color]

[b]18) Operator= 和 Copy构造函数[/b]
a) 何时调用拷贝构造函数,何时调用=
b) 默认拷贝构造函数,默认=操作
c) 指针的问题
d) 实现自检
[color=orange]练习:DoubleContainer的拷贝构造函数[/color]

[b]19) 组合[/b]
[color=orange]练习:用双向链表实现Container[/color]

[b]20) 继承[/b]
a) 子类具有父类所有成员变量和成员函数(直接调用)
b) 子类重定义父类的函数和成员
i. 针对父类的重载函数
ii. 如何在外部调用父类和子类的相关内容
iii. 如何在子类中调用父类的相关内容
c) 非自动继承函数
i. 构造函数,析构函数,copy构造函数,operator=
ii. 函数默认实现方式
iii. 构造函数和析构函数调用次序
iv. 其他操作符重载会被继承
d) 构造函数初始化
i. 区别成员变量的初始化
e) 向上类型转换(值的转换和指针的转换不同)
[color=orange]练习:俄罗斯方块[/color]

[b]21) 多态[/b]
a) 虚函数
i. 强调只能用地址方式的调用获得虚函数的实现
ii. 虚函数必须函数名,函数参数和返回值完全一致,包括const申明,除了返回基类的地址
b) 纯虚函数,抽象类
c) 虚析构函数,纯虚析构函数
d) RTTI
i. 向下类型转换(Static_cast, dynamic_cast)
ii. Typeinfo
[color=orange]练习:俄罗斯方块[/color]

[b]22) 模板介绍[/b]
a) 模板方法
b) 模板类(函数实现放在.h中)
[color=orange]练习:模板Container[/color]

[b]23) 迭代器介绍[/b]
a) 容器vector,类属方法find的简单实现
b) 迭代器演变
c) 五种类型

[b]24) 运算符重载[/b]
a) 成员函数类型的单目运算符重载(前++,后++)
b) 双目运算符重载
i. 全局函数类型的+,-,*,/
ii. 成员函数类型的+=,-=,*=,/=,(检测自赋值)
c) 非成员运算符(<< >>)
d) 自动类型转换
i. 构造函数转换(阻止构造函数转换)
ii. 运算符转换
iii. 解释为什么双目运算符是全局的
[color=orange]练习:Complex类,实现各种运算。
练习:DoubleContainer的[]和=重载
练习:具有Iterator的模板Container[/color]

[b]25) 标准库介绍[/b]
a) 主要容器
i. Vector
ii. Map
iii. Set
b) 算法应用
i. 所有容器的共同操作(==,!=,empty(),size(),clear(),begin(),end(),insert(),erase())
ii. 非可变序列算法(find,count,search)
iii. 可变序列算法(sort, merge, copy,fill,shuffle,remove,replace, reverse,swap)
iv. 迭代器适配器
v. 数值算法(accumulate,)
c) 主要类属方法
d) 函数对象
i. 自定义函数(函数,类)
ii. Stl 函数对象
iii. 函数对象适配器
[color=orange]练习:字符串解析[/color]

[b]26) 其他[/b]
a) Exception
i. 抛出异常
ii. 捕捉异常
iii. 自定义异常
b) 命名空间
i. 尽量小范围使用命名空间
ii. 自定义命名空间

[b]27) 练习:[/b]
GreenCppC 2008-8-24 ========================================= // I 类,对象,函数重载 //-------- From C to C++ ------------ // A simple C Program! // convert a string to uppercase! #include <stdio.h> #define N 200 int main(){ char ms[N]; int i; printf("Input ms: "); gets(ms); for(i=0;ms[i];i++) if(ms[i]>='a'&&ms[i]<='z') ms[i]-='\x20'; puts(ms); return 0; } /* path d:\wingw\bin gcc abc.c -o abc.exe */ //------------------------------ // A better C Program! #include <stdio.h> #define N 200 void strUpper(char *s); void strLower(char *s); int main(){ char ms[N]; printf("Input ms: "); gets(ms); strUpper(ms); puts(ms); strLower(ms); puts(ms); return 0; } void strUpper(char *s) { for(;*s;s++) if(*s>='a'&&*s<='z')*s-='\x20'; } void strLower(char *s) { for(;*s;s++) if(*s>='A'&&*s<='Z')*s+='\x20'; } //------------------------------ // A C++ Program without class and object! #include <iostream> using namespace std; const int N=200; void strUpper(char *s); void strLower(char *s); int main(){ char ms[N]; cout<<"Input ms: "; cin.getline(ms,N); strUpper(ms); cout<<ms<<"\n"; strLower(ms); cout<<ms<<endl; return 0; } void strUpper(char *s) { for(;*s;s++) if(*s>='a'&&*s<='z')*s-='\x20'; } void strLower(char *s) { for(;*s;s++) if(*s>='A'&&*s<='Z')*s+='\x20'; } //------------------------------ // A C++ Program with class and object! #include <iostream> using namespace std; const int N=200; class Str{ char s[N]; public: void out(){cout<<s<<"\n";} void in(){cout<<"s: "; cin.getline(s,N);} void upper(); void lower(); }; void Str::upper() {char *p; for(p=s;*p;p++) if(*p>='a'&&*p<='z')*p-='\x20'; } void Str::lower() { for(char *p=s;*p;p++) if(*p>='A'&&*p<='Z')*p+='\x20'; } // - - - int main(){ Str a; cin>>a.s; //error! a.in(); a.upper(); a.out(); a.lower(); a.out(); return 0; } ========================================= // II. 构造与析构函数 #include <iostream> #include <cstring> using namespace std; class child { char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); ~child(); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *name,int age){ strcpy(this->name,name); this->age=age; // this -- address of self object } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int age){ if(this->age==age) cout<<"Yes, i am "<<age<<" years old.\n"; else cout<<"No, i am not "<<age<<" years old.\n"; } // --- child::~child(){ cout<<name<<": Bye!\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.age=4; // error! tom.ask("tom"); rose.ask("Alice"); tom.ask(2); return 0; } ========================================= // III. 继承 #include <iostream> #include <cstring> using namespace std; class child { protected: //note this change! char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *n,int a){ strcpy(name,n); age=a; } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int a){ if(a==age) cout<<"Yes, i am "<<a<<" years old.\n"; else cout<<"No, i am not "<<a<<" years old.\n"; } // ----------- class pupil: public child{ char book[20]; public: pupil(char *n,int a,char *b); void list(); }; // --- pupil::pupil(char *n,int a,char *b): child(n,a) { strcpy(book,b); } // --- void pupil::list() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.ask("tom"); rose.ask("Alice"); tom.ask(2); pupil green("Green",9,"Nature"); green.ask("Jack"); green.ask(10); green.list(); return 0; } ========================================= // IV. 增加与基类成员函数同名的函数; // 调用基类成员函数;内联函数(in-line) #include <iostream> #include <cstring> using namespace std; class child { protected: char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *n,int a){ strcpy(name,n); age=a; } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int a){ if(a==age) cout<<"Yes, i am "<<a<<" years old.\n"; else cout<<"No, i am not "<<a<<" years old.\n"; } // ----------- class pupil: public child{ char book[20]; public: pupil(char *n,int a,char *b); void ask(char *n){child::ask(n);} // in-line! void ask(int a){child::ask(a);} void ask(); }; // --- pupil::pupil(char *n,int a,char *b): child(n,a) { strcpy(book,b); } // --- void pupil::ask() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.ask("tom"); rose.ask("Alice"); tom.ask(2); pupil green("Green",9,"Nature"); green.ask("Jack"); green.ask(10); green.ask(); return 0; } ===================================== // V. 对象数组 #include <iostream> using namespace std; class C1{ int a,b; public: C1(int m,int n){a=m;b=n;} int getAdd(){return a+b;} }; int main() {C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)}; int i; for(i=0;i<3;i++) cout << ob[i].getAdd() << " "; // C1 oe[2]; -- Error! means constructor is C1() // -- need reload C1::C1(){ ... } // -- eg, C1::C1(){a=b=0;} return 0; } ========================================= // VI. 指向对象的指针 C1 obA(2,3), *p; p=&obA; cout << p->getAdd(); //------------- C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)}, *q; q=ob; for(int i=0;i<3;i++) {cout << q->getAdd() << " "; q++; } //------------- class C2{ public: int a; C2(int k){a=k*k;} }; // . . . C2 obB(9); int *p; p=&obB.a; // Note! a is public, p to member cout << *p; // 指向派生类的指针 class Base{ public: int a,b; Base(int m,int n){a=m;b=n;} int getAdd(){return a+b;} }; class Derived: public Base{ int c; public: Derived(int x,int y,int z): Base(x,y) {c=z;} float getAve(){return (a+b+c)/3.0F;} }; // ... Base *bp; Derived d(6,7,9); bp=&d; cout << bp->getAdd(); cout << bp->getAve(); // Error! cout << ((Derived *) bp) ->getAve(); ========================================= // VII. 动态分配:new, delete #include <iostream> #include <new> using namespace std; int main() {int *p; try{ p=new int; } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } *p=20; cout << "At "<<p<<" is "<< *p <<"\n"; delete p; return 0; } //------------- #include <iostream> #include <new> using namespace std; int main() {int *p; try{ p=new int[6]; } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } float ave=0.0F; int i; cout<<"Enter numbers: "; for(i=0;i<6;i++) {cin>>p[i]; ave+= *(p+i); cout<< *(p+i); } ave/=6.0F; cout << "Ave = "<< ave <<"\n"; delete [] p; return 0; } //------------- #include <iostream> #include <cstring> #include <new> using namespace std; class Balance{ char name[40]; double curValue; public: Balance(char *n,double v){ strcpy(name,n); curValue=v; } void getValue(char *n,double &v){ strcpy(n,name); v=curValue; } }; int main() { Balance *p; char s[40]; double bal; try{ p=new Balance("Robin Hood",3536.45); } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } p->getValue(s,bal); cout<<s<<"\'s balance is "<<bal<<"\n"; delete p; return 0; } ========================================= // VIII. 传递引用 #include <iostream> using namespace std; void neg1(int k); void neg2(int *p); void neg3(int &k); int main() { int x=20; neg1(x); neg2(&x); cout << x<< "\n"; neg3(x); cout << x<< "\n"; } // - - - void neg1(int k) { k=-k;} void neg2(int *p) { *p=-*p;} void neg3(int &k) { k=-k; } //------------- #include <iostream> using namespace std; class C1{ public: int k; void neg(C1 &o){o.k=-o.k;} // -- no temp object created }; int main() { C1 ob; ob.k=20; ob.neg(ob); cout << ob.k <<"\n"; return 0; } //----------------------------------- /* Input a sentence,reverse all the words except other chars, eg: etihw, dna kcalb! => white, and black! NOT: !black and ,white */ #include <iostream> #include <new> #include <cstdlib> #include <cctype> using namespace std; const int N=200; /* - - - - - - */ class CharStack{ const int StkLen; char *data; int top; public: CharStack(); ~CharStack(){delete []data;} int push(char x) {if(top>=StkLen-1)return -1; // it's full top++; data[top]=x; return 0; } int pop(char &x) {if(top<=-1)return -1; // empty! x= *(data+top); top--; return 0; } }; CharStack::CharStack():StkLen(40) {try{ data=new char[StkLen]; }catch(bad_alloc){cout<<"New failed!"; exit(-1);} top=-1; } // --------- class WordRev{ char ms[N]; public: void reads() { cout<<"Input str:\n"; cin.getline(ms,N); } void prints() { cout<<ms<<"\n"; } void wRev(); }; void WordRev::wRev() {CharStack stk; int i=0,wStart,wEnd; while(ms[i]) {if(!isalpha(ms[i]))i++; else {wStart=i; while(isalpha(ms[i]))stk.push(ms[i++]); wEnd=i; i=wStart; while(!stk.pop(ms[i]))i++; i=wEnd; } } } // --------- int main() { WordRev sr; sr.reads(); sr.wRev(); sr.prints(); return 0; } ========================================= // IX 函数形参使用默认值 #include <iostream> #include <cstring> using namespace std; // ----------- class pupil{ public: char name[20]; int age; char book[20]; pupil(char *n,int a,char *b); void list(); }; // --- pupil::pupil(char *n,int a,char *b){ strcpy(name,n); age=a; strcpy(book,b); } // --- void pupil::list() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- void nextYear(pupil &c,char *book="Math"); //---------- int main(){ pupil green("Green",9,"Chinese"); green.list(); nextYear(green); green.list(); nextYear(green,"Nature"); green.list(); return 0; } //---------- void nextYear(pupil &c,char *book="Math") { // ="Math" Should be omitted, for previous prototype c.age++; strcpy(c.book,book); return; } /* D:\green>g++ pupil.cpp -o pupil.exe pupil.cpp: In function `void nextYear(pupil&, char*)': pupil.cpp:41: error: default argument given for parameter 2 of `void nextYear(pupil&, char*)' pupil.cpp:25: error: after previous specification in `void nextYear(pupil&, char*)' */ ========================================= // X. 虚函数 virtual #include <iostream> using namespace std; class base{ public: virtual void vf(){cout<<"base's vf.\n";} }; class derived1:public base{ public: virtual void vf(){cout<<"derived1's vf.\n";} }; class derived2:public base{ public: virtual void vf(){cout<<"derived2's vf.\n";} }; void f(base &r){r.vf();} int main() {base b, *p; derived1 d1; derived2 d2; b.vf(); d1.vf(); d2.vf(); p=&b; p->vf(); p=&d1; p->vf(); // derived1's vf. p=&d2; p->vf(); // derived2's vf. f(b); f(d1); // derived1's vf. f(d2); // derived2's vf. return 0; } ========================================= // XI. 对象赋值问题 #include <iostream> #include <cstdlib> #include <new> using namespace std; class Myclass{ int *p; public: Myclass(int i); void show(){cout<< *p<<"\n";} ~Myclass(){delete p;} }; Myclass::Myclass(int i){ try{ p=new int; } catch(bad_alloc e) {cout<< "New failed!\n"; exit(-1); } *p=i; } int main() {Myclass a(20); Myclass b=a; //copy by bits b.show(); return 0; // 错误!对象中 p 所指向的内存空间将被释放 2 次! } ========================================= // XII. 拷贝构造函数 ---- 解决对象参数传递的副作用问题 #include <iostream> #include <new> using namespace std; class array{ public: int *p; int size; array( ){p=NULL;size=0; }; array(int sz); array(const array &a); ~array(){if(!p){delete [ ]p; size=0;}} void input(); }; array::array(int sz){ size=sz; try{ p=new int[size]; }catch (bad_alloc xa){ cout <<"Alloc failed!"; exit(EXIT_FAILURE); } } array::array(const array &a){ try{ p=new int[a.size]; }catch (bad_alloc xa){ cout <<"Alloc failed!"; exit(EXIT_FAILURE); } size=a.size; for(int i=0;i<size;i++)p[i]=a.p[i]; } void array::input(){ cout<<"Input "<<size<<" integers: "; for(int i=0;i<size;i++)cin>>p[i]; } void inc(array a){ int i; for(i=0;i<a.size;i++) if(a.p[i]==59)a.p[i]++; cout<<"Result is: " ; for(i=0;i<a.size;i++)cout<<a.p[i]<<' '; cout<<"\n"; } int main(){ array a(4),c; a.input(); array b(a); // 调用拷贝构造函数 inc(b); //调用拷贝构造函数(隐式) for(int i=0;i<b.size;i++)cout<<b.p[i]<<' '; return 0; } ========================================= // XIII. 运算符重载 #include <iostream> using namespace std; class loc{ int longitude,latitude; public: loc(){} //needed to construct temp objects loc(int lg,int lt){longitude=lg; latitude=lt;} void show(){cout<<longitude<<" "<<latitude<<"\n";} loc operator+(loc op2); loc operator++(); loc operator=(loc op2); loc operator+=(loc op2); }; loc loc::operator+(loc op2) {loc temp; temp.longitude=op2.longitude+longitude; temp.latitude=op2.latitude+latitude; return temp; } loc loc::operator++() //前缀形式 prefix {longitude++; latitude++; return *this; } loc loc::operator=(loc op2) { longitude=op2.longitude; latitude=op2.latitude; return *this; //为连续赋值 } loc loc::operator+=(loc op2) { longigude=op2.longitude+longitude; latitude=op2.latitude+latitude; return *this; //为连续赋值 } // operator=和operator++等都改变了对象的值 int main() {loc ob1(10,20),ob2(5,30),ob3; ob3=ob1+ob2; ++ob3; ob3.show(); ob1+=ob2; ob1=ob1+ob2; // ob1.+(ob2) like (ob1+ob2).show(); ++ob1; ob1=ob2=ob3; ... ... } ========================================= // XIV. 异常的抛出,捕获与处理 #include <iostream> using namespace std; int main() {cout <<"Start\n"; try { cout << "Inside try block\n"; throw 100; cout << "This will not execute"; } catch (int i) { cout << "Caught an exception, value is: "; cout << i <<"\n"; } cout << "End\n"; return 0; } // -------------------- #include <iostream> using namespace std; void xtest(int test) { cout << "Inside xtest!\n"; if(test) throw test; } int main() {cout <<"Start\n"; try { cout << "Inside try block\n"; xtest(0); xtest(1); xtest(2); } catch (int i) { cout << "Caught an exception, value is: "; cout << i <<"\n"; } cout << "End\n"; return 0; } // 捕获异常类 #include <iostream> #include <cstring> using namespace std; class MyException{ public: char how[80]; int what; MyException(){*how=0; what=0;} MyException(char *s, int n) {strcpy(how,s); what=n; } }; int main() {int i; try { cout <<"Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive",i); } catch (MyException e) { cout << e.how<<": "; cout << e.what <<"\n"; } return 0; } // 捕获派生异常类 #include <iostream> using namespace std; class B { }; class D: public B { }; int main() {D derived; try { throw derived; } catch (D d) { cout << "Caught a derived class, not the base! \n"; } catch (B b) { cout << "Caught the base class! \n"; } return 0; } // 异常的限制及捕获所有异常 #include <iostream> using namespace std; void xtest(int test) throw (int,char,double,char *) { try { if(test==0) throw test; if(test==1) throw 'a'; if(test==2) throw 12.34; if(test==3) throw "A string."; } catch (int i) { cout << "Caught an integer!"; } catch (...) { cout << "Caught Another!"; } } int main() {cout <<"Start\n"; xtest(0); xtest(1); xtest(2); xtest(3); cout << "End\n"; return 0; } // 异常的再次抛出 #include <iostream> using namespace std; void xhandler() { try { throw "Hello!"; } catch (const char *) { cout << "Caught a string inside!\n"; throw; //rethrow char * out of function } } int main() {cout <<"Start\n"; try { xhandler(); } catch (const char *) { cout << "Caught a string outside!\n"; } cout << "End\n"; return 0; } // 一个简单的程序 #include <iostream> using namespace std; int main() {int a,b; cout <<"Enter a b: "; cin >> a >> b; try { if(!b) throw b; cout << "Result: "<< a/b << endl; } catch (int i) { cout << "Can't divide by zero!\n"; } return 0; } ========================================= XV. 模板 //模板之通用函数 #include <iostream> using namespace std; template <class X> void superSwap(X &a, X &b) { X t; t=a; a=b; b=t; }; int main() { int m=10, n=20; double x=10.1, y=20.2; char a='A', b='\x42'; superSwap(m,n); superSwap(x,y); superSwap(a,b); cout<<"m="<<m<<", n="<<n<<'\n'; cout<<"x="<<x<<", y="<<y<<'\n'; cout<<"a="<<a<<", b="<<b<<'\n'; return 0; } ---------------------------------- #include <iostream> using namespace std; template <class type1,class type2> void myfunc(type1 x, type2 y) { cout<<x<<' '<<y<<'\n'; } int main() { myfunc("C++ is great!", 100); // char* , int myfunc(1234.56, 20L); // double , long int return 0; } // 模板之通用类 #include <iostream> using namespace std; const int Size=20; template <class DataType> class SuperStack{ DataType data[Size]; int top; public: SuperStack(){top= -1;} int push(DataType x); int pop(DataType &x); }; template <class DataType> int SuperStack<DataType>::push(DataType x) { if(top>=Size-1) return -1; // stack is full data[++top]=x; return 0; } template <class DataType> int SuperStack<DataType>::pop(DataType &x) { if(top<0) return -1; // stack is empty x=data[top--]; return 0; } int main() { SuperStack<char> chStack; SuperStack<double> dbStack; char s[Size]="ABC"; double a[Size]={20.1, 21.2, 22.3}; int i; for(i=0;i<3;i++) { chStack.push(s[i]); dbStack.push(a[i]); } for(i=0;i<3;i++) { chStack.pop(s[i]); dbStack.pop(a[i]); } cout << s << '\n'; for(i=0;i<3;i++) cout << a[i]<<' '; cout<<'\n'; return 0; } ========================================= XVI. 名字空间 #include <iostream> using namespace std; namespace GreenNamespace{ char Say[80]="TRUTH, Must thou Know!"; bool isUpperLetter(char ch) { if(ch>='A' &&ch<='Z')return true; return false; } class X{ public: int year; X(int y){year=y;} }; // note this semi-colon! } using namespace GreenNamespace; int main() {cout << Say <<'\n'; char *p=Say; int count=0; for(;*p;p++) if(isUpperLetter(*p))count++; cout << "count = " << count <<'\n'; X ob(2006); cout << ob.year <<"\n"; return 0; } //------------------------ ////////// OneCount.cpp//////// namespace BitsSpace{ int onePerByte(char x); int oneCount(char *buf,int bytes); // ------------------- int onePerByte(char x) {int count=0,i; for(i=0;i<8;i++) {if(x & '\x1') count++; // 'A'<=> '\x41' x>>=1; //x=x>>1; } return count; } // --- int oneCount(char *buf,int bytes) {int count=0,i; for(i=0;i<bytes;i++) count+=onePerByte(buf[i]); return count; } // --- } ---------------- ////////// testOne.cpp//////// #include <iostream> #include "OneCount.cpp" using namespace std; //using namespace BitsSpace; const int SLen=80; // ---- int main(){ char ms[SLen],*p; cout<<"Enter your words:\n> " ; cin.getline(ms,SLen); cout<< BitsSpace::oneCount(ms,strlen(ms))<<"\n"; cout<<"Size of char: "<<sizeof(char)<<"\n"; return 0; } ========================================= //////////////////////////////// // XVII. C++ file handle, 6 programs // by Hs.li 2007.4.28 //////////////////////////////// // Write text strings! #include <iostream> #include <fstream> using namespace std; #define MaxN 200 // - - - - - - int main() {fstream outF; char text[MaxN]; cout<<"Enter lines, end with empty line:\n"; outF.open("str.txt",ios::out); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } while(1) { cin.getline(text,MaxN); if(!text[0])break; outF<<text<<"\n"; if(outF.bad()||outF.fail()) {cout<<"Write file error!\n"; outF.close(); return -2; } } cout<<"Write text file okey!\n"; outF.close(); return 0; } ========================= // Read text strings! #include <iostream> #include <fstream> using namespace std; #define MaxN 200 // - - - - - - int main() {fstream inF; char text[MaxN]; cout<<"The text lines are:\n"; inF.open("str.txt",ios::in); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } while(1) { inF.getline(text,MaxN); if(inF.eof()|inF.fail()|inF.bad())break; cout<<text<<"\n"; } if(!inF.eof()) {cout<<"Read file error!\n"; inF.close(); return -2; } cout<<"---- End!\n"; inF.close(); return 0; } ====================== // Write text data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { const int MaxN=8; fstream outF; double a[MaxN]; char *fname="data.txt"; int i; cout<<"Please input 8 double: "; for(i=0;i<MaxN;i++) cin>>a[i]; outF.open(fname,ios::out); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } outF.exceptions(fstream::failbit| fstream::badbit); try{ for(i=0;i<MaxN;i++) outF<<a[i]<<" "; } catch(std::exception &e) {cout<<"Exception caught:"<<e.what()<<endl; outF.close(); return -2; } outF.close(); cout<<"Text data file write okey!\n"; return 0; } ============================ // Read text data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { fstream inF; double b; char *fname="data.txt"; cout<<"Please wait for reading data:\n"; inF.open(fname,ios::in); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } inF.exceptions(fstream::failbit| fstream::badbit|fstream::eofbit); try{ while(1) { inF>>b; cout<<b<<" "; } }catch(std::exception &e) { if(!inF.eof()) { cout<<"Exception caught:"<<e.what()<<endl; inF.close(); return -2; } } inF.close(); cout<<"\nText data file read okey!\n"; return 0; } =============================== // Write binary data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { const int MaxN=8; fstream outF; double a[MaxN]; char *fname="data.dat"; int i; cout<<"Please input 8 double: "; for(i=0;i<MaxN;i++) cin>>a[i]; outF.open(fname,ios::out|ios::binary); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } outF.exceptions(fstream::failbit| fstream::badbit); try{ outF.write((char *)a,MaxN*sizeof(double)); } catch(std::exception &e) {cout<<"Exception caught:"<<e.what()<<endl; outF.close(); return -2; } outF.close(); cout<<"Binary data file write okey!\n"; return 0; } ================================ // Read binary data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { fstream inF; double b; char *fname="data.dat"; cout<<"Please wait for reading data:\n"; inF.open(fname,ios::in|ios::binary); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } inF.exceptions(fstream::failbit| fstream::badbit|fstream::eofbit); try{ while(1) { inF.read((char *)&b,sizeof(double)); cout<<b<<" "; } }catch(std::exception &e) { if(!inF.eof()) { cout<<"Exception caught:"<<e.what()<<endl; inF.close(); return -2; } } inF.close(); cout<<"\nBinary data file read okey!\n"; return 0; } ////////////////////////////////////////////////
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值