代码重用是现代程序设计追求的一个重要目标,模板有效地软件重用。模板和异常处理都是c++的重要机制。利用模板可以大大缩短了程序的长度。
 #include<iostream>
 using namespace std;
 template<class T>
 class A{
T x;
T y;
     public:
A(T a,T b){
x=a;
y=b;
}
void display(){
cout<<x<<"+"<<y<<"i"<<endl;
} 
 };
  
 int main(){
     A<int>a1(2,3);
A<double>a2(4.3,5.3);
a1.display();
a2.display(); 
    
    return 0;
 } 
 函数模板
 #include<iostream>
 using namespace std;
 template<class T>
 T sum(T a,T b){       //加法模板 
return a+b;
 } 
 int isum(int a,int b){  //整数加法 
return a+b;
 } 
 float fsum(float a,float b){ // 实数加法 
return a+b;
 }
 int main(){
     cout<<"isum(2,3)="<<isum(2,3)<<endl;
cout<<"fsum(3.5,4.12)="<<fsum(3.5,4.1)<<endl;
     cout<<"sum(2,3)="<<sum(2,3)<<endl;
cout<<"sum(3.5,4.12)="<<sum(3.5,4.1)<<endl;
    return 0;
 } 
 sum其实相当于若干个函数的组合,对于不同的参数类型,sum可以返回不同的结果
 异常处理是c++的一个特点,它能够检测到程序运行错误后终止程序,并按照指定的方法对错误进行处理,当异常被处理完之后,程序又开始运行。
 #include<iostream>
 using namespace std;
 class YC{};
 int main(){
    double a,b,c;
    cin>>a>>b>>c;
    try{
     if(c==0)
       throw YC();
       cout<<a<<"+"<<b<<"/"<<c<<"="<<a+b/c<<endl;
    }
    catch(YC){
     cout<<"除数不可以为0 "<<endl;
    }
    return 0;
 } 
 #include<iostream>
 using namespace std;
 class YC1{};
 class YC2{};
 int main(){
    int a,b;
    cin>>a>>b;
    try{
     if(a*b<10)
       throw YC1();
     else if(a*b>100)
        throw YC2();
      cout<<"该矩形的面积为 "<<a*b<<"平方米"<<endl;
       
    }
    catch(YC1){
         cout<<"面积不可以小于10"<<endl; 
    }
    catch(YC2){
     cout<<"面积不可以大于100"<<endl;
    }
    return 0;
 }
 多少种情况就抛出多少个异常
 文件
 #include<iostream>
 #include<fstream>
 using namespace std;
 int main(){
     ofstream ofile("11111.txt"); //以文本形式打开文件 
     if(!ofile)
        cerr<<"打开文件错误"<<endl;
     else{        //开始写入操作 
        ofile<<"姓名\t"<<"年龄\t"<<"性别\t"<<endl;
        ofile<<"赵易\t"<<"21\t"<<"男\t"<<endl;
        ofile<<"杜帅\t"<<"20\t"<<"男\t"<<endl;
        ofile<<"赵彤彤\t"<<"20\t"<<"女\t"<<endl;
     } 
    return 0;
 } 
 #include<iostream>
 #include<fstream>
 using namespace std;
 int main(){
     ofstream ofile;
ifstream ifile;
char buf1[30],buf2[30];
ofile.open("11111.txt");//打开文件。写入 
ofile<<"hello 彤彤";
ofile<<"I Love You";
ofile.close();//关闭文件
ifile.open("11111.txt");  //打开文件,进行读操作 
     ifile.getline(buf1,30);
     ifile.getline(buf2,30);
     cout<<buf1<<endl;
     cout<<buf2<<endl;
    return 0;
 } 
 <<endl,在文件读取过程中,这个会读到文件中去。