13C++异常处理

异常处理


14.1.1 异常处理的任务

程序编制者不仅要考虑程序没有错误的理想情况,更要考虑程序存在错误时的情况,应该能够尽快地发现错误,消除错误。

程序中常见的错误有两大类: 语法错误和运行错误。在编译时,编译系统能发现程序中的语法错误。

有的程序虽然能通过编译,也能投入运行。但是在运行过程中会出现异常,得不到正确的运行结果,甚至导致程序不正常终止,或出现死机现象。这类错误比较隐蔽,不易被发现,往往耗费许多时间和精力。这成为程序调试中的一个难点。

在设计程序时,应当事先分析程序运行时可能出现的各种意外的情况,并且分别制订出相应的处理方法,这就是程序的异常处理的任务。

在运行没有异常处理的程序时,如果运行情况出现异常,由于程序本身不能处理,程序只能终止运行。如果在程序中设置了异常处理机制,则在运行情况出现异常时,由于程序本身已规定了处理的方法,于是程序的流程就转到异常处理代码段处理。用户可以指定进行任何的处理。

需要说明,只要出现与人们期望的情况不同,都可以认为是异常,并对它进行异常处理。因此,所谓异常处理指的是对运行时出现的差错以及其他例外情况的处理。

14.1.2 异常处理的方法

在一个小的程序中,可以用比较简单的方法处理异常。但是在一个大的系统中,如果在每一个函数中都设置处理异常的程序段,会使程序过于复杂和庞大。因此,C++采取的办法是: 如果在执行一个函数过程中出现异常,可以不在本函数中立即处理,而是发出一个信息,传给它的上一级(即调用它的函数),它的上级捕捉到这个信息后进行处理。如果上一级的函数也不能处理,就再传给其上一级,由其上一级处理。如此逐级上送,如果到最高一级还无法处理,最后只好异常终止程序的执行。

这样做使异常的发现与处理不由同一函数来完成。好处是使底层的函数专门用于解决实际任务,而不必再承担处理异常的任务,以减轻底层函数的负担,而把处理异常的任务上移到某一层去处理。这样可以提高效率。

C++处理异常的机制是由3个部分组成的,即检查(try)、抛出(throw)和捕捉(catch)。把需要检查的语句放在try块中,throw用来当出现异常时发出一个异常信息,而catch则用来捕捉异常信息,如果捕捉到了异常信息,就处理它。

例14.1 给出三角形的三边a,b,c,求三角形的面积。只有a+b>c,b+c>a,c+a>b时才能构成三角形。设置异常处理,对不符合三角形条件的输出警告信息,不予计算。

先写出没有异常处理时的程序:

#include <iostream>

#include <cmath>

using namespace std;

int main( )

{double triangle(double,double,double);

 double a,b,c;

 cin>>a>>b>>c;

 while(a>0 && b>0 && c>0)

  {cout<<triangle(a,b,c)<<endl;

   cin>>a>>b>>c;

  }

  return 0;

}

 

double triangle(double a,double b,double c)

{double area;

 double s=(a+b+c)/2;

 area=sqrt(s*(s-a)*(s-b)*(s-c));

 return area;

}

运行情况如下:

6 5 4↙(输入a,b,c的值)

9.92157             (输出三角形的面积)

1 1.5 2↙           (输入a,b,c的值)

0.726184            (输出三角形的面积)

1 2 1↙             (输入a,b,c的值)

0                   (输出三角形的面积,此结果显然不对,因为不是三角形)

1 0 6↙             (输入a,b,c的值)

(结束)

修改程序,在函数traingle中对三角形条件进行检查,如果不符合三角形条件,就抛出一个异常信息,在主函数中的try-catch块中调用traingle函数,检测有无异常信息,并作相应处理。修改后的程序如下:

#include <iostream>

#include <cmath>

using namespace std;

void main( )

{double triangle(double,double,double);

 double a,b,c;

 cin>>a>>b>>c;

 try//在try块中包含要检查的函数

  {while(a>0 && b>0 && c>0)

    {cout<<triangle(a,b,c)<<endl;

   cin>>a>>b>>c;

    }

  }

catch(double)                       //用catch捕捉异常信息并作相应处理

  {cout<<″a=″<<a<<″,b=″<<b<<″,c=″<<c<<″,that is not a triangle!″<<endl;}

 cout<<″end″<<endl;

}

 

double triangle(double a,double b,double c)  //计算三角形的面积的函数

{double s=(a+b+c)/2;

 if (a+b<=c||b+c<=a||c+a<=b) throw a;   //当不符合三角形条件抛出异常信息

 return sqrt(s*(s-a)*(s-b)*(s-c));

}

程序运行结果如下:

6 5 4↙(输入a,b,c的值)

9.92157             (计算出三角形的面积)

1 1.5 2↙           (输入a,b,c的值)

0.726184            (计算出三角形的面积)

1 2 1↙             (输入a,b,c的值)

a=1,b=2,c=1, that is not a triangle!  (异常处理)

end

现在结合程序分析怎样进行异常处理。

(1) 首先把可能出现异常的、需要检查的语句或程序段放在try后面的花括号中。

(2) 程序开始运行后,按正常的顺序执行到try块,开始执行try块中花括号内的语句。如果在执行try块内的语句过程中没有发生异常,则catch子句不起作用,流程转到catch子句后面的语句继续执行。

(3) 如果在执行try块内的语句(包括其所调用的函数)过程中发生异常,则throw运算符抛出一个异常信息。throw抛出异常信息后,流程立即离开本函数,转到其上一级的函数(main 函数)。

throw抛出什么样的数据由程序设计者自定,可以是任何类型的数据。

(4) 这个异常信息提供给try-catch结构,系统会寻找与之匹配的catch子句。

(5) 在进行异常处理后,程序并不会自动终止,继续执行catch子句后面的语句。

由于catch子句是用来处理异常信息的,往往被称为catch异常处理块或catch异常处理器。

下面讲述异常处理的语法。

throw语句一般是由throw运算符和一个数据组成的,其形式为

throw 表达式;

try-catch的结构为

try

      {被检查的语句}

catch(异常信息类型 [变量名])

      {进行异常处理的语句}

说明:

(1) 被检测的函数必须放在try块中,否则不起作用。

(2) try块和catch块作为一个整体出现,catch块是try-catch结构中的一部分,必须紧跟在try块之后,不能单独使用,在二者之间也不能插入其他语句。但是在一个try-catch结构中,可以只有try块而无catch块。即在本函数中只检查而不处理,把catch处理块放在其他函数中。

(3) try和catch块中必须有用花括号括起来的复合语句,即使花括号内只有一个语句,也不能省略花括号。

(4) 一个try-catch结构中只能有一个try块,但却可以有多个catch块,以便与不同的异常信息匹配。

(5) catch后面的圆括号中,一般只写异常信息的类型名, 如

catch(double)

catch只检查所捕获异常信息的类型,而不检查它们的值。因此如果需要检测多个不同的异常信息,应当由throw抛出不同类型的异常信息。

异常信息可以是C++系统预定义的标准类型,也可以是用户自定义的类型(如结构体或类)。如果由throw抛出的信息属于该类型或其子类型,则catch与throw二者匹配,catch捕获该异常信息。

catch还可以有另外一种写法,即除了指定类型名外,还指定变量名,如

catch(double d)

此时如果throw抛出的异常信息是double型的变量a,则catch在捕获异常信息a的同时,还使d获得a的值,或者说d得到a的一个拷贝。什么时候需要这样做呢?有时希望在捕获异常信息时,还能利用throw抛出的值,如

catch(double d)

  {cout<<″throw ″<<d;}

这时会输出d的值(也就是a值)。当抛出的是类对象时,有时希望在catch块中显示该对象中的某些信息。这时就需要在catch的参数中写出变量名(类对象名)。

(1)   如果在catch子句中没有指定异常信息的类型,而用了删节号“…”,则表示它可以捕捉任何类型的异常信息,如

catch(…) {cout<<″OK″<<endl;}

它能捕捉所有类型的异常信息,并输出″OK″。

这种catch子句应放在trycatch结构中的最后,相当于“其他”。如果把它作为第一个catch子句,则后面的catch子句都不起作用。

(2)   trycatch结构可以与throw出现在同一个函数中,也可以不在同一函数中。当throw抛出异常信息后,首先在本函数中寻找与之匹配的catch,如果在本函数中无trycatch结构或找不到与之匹配的catch,就转到离开出现异常最近的trycatch结构去处理。

(8) 在某些情况下,在throw语句中可以不包括表达式,如

throw;

表示“我不处理这个异常,请上级处理”。

(9) 如果throw抛出的异常信息找不到与之匹配的catch块,那么系统就会调用一个系统函数terminate,使程序终止运行。

例14.2 在函数嵌套的情况下检测异常处理。

这是一个简单的例子,用来说明在try块中有函数嵌套调用的情况下抛出异常和捕捉异常的情况。请自己先分析以下程序。

#include <iostream>

using namespace std;

int main( )

{void f1( );

 try

  {f1( );}//调用f1( )

 catch(double)

  {cout<<″OK0!″<<endl;}

 cout<<″end0″<<endl;

 return 0;

}

void f1( )

{void f2( );

 try

  {f2( );}                      //调用f2( )

 catch(char)

  {cout<<″OK1!″;}

 cout<<″end1″<<endl;

}

 

void f2( )

{void f3( );

 try

 {f3( );}                      //调用f3( )

 catch(int)

 {cout<<″Ok2!″<<endl;}

 cout<<″end2″<<endl;

}

void f3( )

{double a=0;

 try

  {throw a;}               //抛出double类型异常信息

 catch(float)

  {cout<<″OK3!″<<endl;}

 cout<<″end3″<<endl;

}

                       

(2) 如果将f3函数中的catch子句改为catch(double),而程序中其他部分不变,则程序运行结果如下:

OK3!(在f3函数中捕获异常)

end3                   (执行f3函数中最后一个语句时的输出)

end2                   (执行f2函数中最后一个语句时的输出)

end1                   (执行f1函数中最后一个语句时的输出)

end0                   (执行主函数中最后一个语句时的输出)

(3) 如果在此基础上再将f3函数中的catch块改为

catch(double)

  {cout<<″OK3!″<<endl;throw;}

程序运行结果如下:

OK3!(在f3函数中捕获异常)

OK0!                  (在主函数中捕获异常)

end0                  (执行主函数中最后一个语句时的输出)

14.1.3 在函数声明中进行异常情况指定

为便于阅读程序,使用户在看程序时能够知道所用的函数是否会抛出异常信息以及异常信息可能的类型,C++允许在声明函数时列出可能抛出的异常类型,如可以将例14.1中第二个程序的第3行改写为

double triangle(double,double,double) throw(double);

表示triangle函数只能抛出double类型的异常信息。如果写成

double triangle(double,double,double) throw(int,double,float,char);

则表示triangle函数可以抛出int,double,float或char类型的异常信息。异常指定是函数声明的一部分,必须同时出现在函数声明和函数定义的首行中,否则在进行函数的另一次声明时,编译系统会报告“类型不匹配”。

如果在声明函数时未列出可能抛出的异常类型,则该函数可以抛出任何类型的异常信息。如例14.1中第2个程序中所表示的那样。

如果想声明一个不能抛出异常的函数,可以写成以下形式:

double triangle(double,double,double) throw();//throw无参数

这时即使在函数执行过程中出现了throw语句,实际上也并不执行throw语句,并不抛出任何异常信息,程序将非正常终止。

14.1.4 在异常处理中处理析构函数

如果在try块(或try块中调用的函数)中定义了类对象,在建立该对象时要调用构造函数。在执行try块 (包括在try块中调用其他函数) 的过程中如果发生了异常,此时流程立即离开try块。这样流程就有可能离开该对象的作用域而转到其他函数,因而应当事先做好结束对象前的清理工作,C++的异常处理机制会在throw抛出异常信息被catch捕获时,对有关的局部对象进行析构(调用类对象的析构函数), 析构对象的顺序与构造的顺序相反,然后执行与异常信息匹配的catch块中的语句。

例14.3 在异常处理中处理析构函数。

这是一个为说明在异常处理中调用析构函数的示例,为了清晰地表示流程,程序中加入了一些cout语句,输出有关的信息,以便对照结果分析程序。

#include <iostream>

#include <string>

using namespace std;

class Student

{public:

   Student(int n,string nam)//定义构造函数

{cout<<″constructor-″<<n<<endl;

num=n;name=nam;}

~Student( ){cout<<″destructor-″<<num<<endl;}//定义析构函数

   void get_data( );                                 //成员函数声明

private:

int num;

string name;

 };

void Student::get_data( )                           //定义成员函数

{if(num==0) throw num;                            //如num=0,抛出int型变量num

  else cout<<num<<″ ″<<name<<endl;                 //若num≠0,输出num,name

  cout<<″in get_data()″<<endl;                     //输出信息,表示目前在get_data函数中

 }

 

void fun( )

{Student stud1(1101,″Tan″);               //建立对象stud1

stud1.get_data( );                        //调用stud1的get_data函数

Student stud2(0,″Li″);                   //建立对象stud2

stud2.get_data( );                        //调用stud2的get_data函数

}

 

int main( )

{cout<<″main begin″<<endl;                 //表示主函数开始了

cout<<″call fun( )″<<endl;                 //表示调用fun函数

try

  {fun( );}                                 //调用fun函数

catch(int n)

  {cout<<″num=″<<n<<″,error!″<<endl;}      //表示num=0出错

cout<<″main end″<<endl;                   //表示主函数结束

return 0;

}

程序运行结果如下:

main begin

call fun( )

constructor-1101

1101 tan

in get_data()

constructor-0

destructor-0

destructor-1101

num=0,error!

main end

14.2 命名空间

在学习本书前面各章时,已经多次看到在程序中用了以下语句:

using namespace std;

这就是使用了命名空间std。在本节中将对它作较详细的介绍。

14.2.1 为什么需要命名空间

命名空间是ANSI C++引入的可以由用户命名的作用域,用来处理程序中常见的同名冲突。

在C语言中定义了3个层次的作用域,即文件(编译单元) 、函数和复合语句。C++又引入了类作用域,类是出现在文件内的。在不同的作用域中可以定义相同名字的变量,互不干扰,系统能够区别它们。

下面先简单分析一下作用域的作用,然后讨论命名空间的作用。

如果在文件中定义了两个类,在这两个类中可以有同名的函数。在引用时,为了区别,应该加上类名作为限定,如

class A//声明A类

 {public:

void fun1( );         //声明A类中的fun1函数

  private:

int i;

 };

void A::fun1( )             //定义A类中的fun1函数

 {

//

 }

class B                   //声明B类

 {public:

void fun1( );          //B类中也有fun1函数

void fun2( );

 };

void B::fun1( )             //定义B类中的fun1函数

 {

   //

 }

这样不会发生混淆。

在文件中可以定义全局变量(global variable),它的作用域是整个程序。如果在文件A中定义了一个变量a

int a=3;

在文件B中可以再定义一个变量a

int a=5;

在分别对文件A和文件B进行编译时不会有问题。但是,如果一个程序包括文件A和文件B,那么在进行连接时,会报告出错,因为在同一个程序中有两个同名的变量,认为是对变量的重复定义。问题在于全局变量的作用域是整个程序,在同一作用域中不应有两个或多个同名的实体(entity),包括变量、函数和类等。 

可以通过extern声明同一程序中的两个文件中的同名变量是同一个变量。如果在文件B中有以下声明:

extern int a;

表示文件B中的变量a是在其他文件中已定义的变量。由于有此声明,在程序编译和连接后,文件A的变量a的作用域扩展到了文件B。如果在文件B中不再对a赋值,则在文件B中用以下语句输出的是文件A中变量 a的值:

cout<<a;//得到a的值为3

在简单的程序设计中,只要人们小心注意,可以争取不发生错误。但是,一个大型的应用软件,往往不是由一个人独立完成的,假如不同的人分别定义了类,放在不同的头文件中,在主文件(包含主函数的文件)需要用这些类时,

就用#include命令行将这些头文件包含进来。由于各头文件是由不同的人设计的,有可能在不同的头文件中用了相同的名字来命名所定义的类或函数。这样在程序中就会出现名字冲突。

例14.4 名字冲突。

程序员甲在头文件header1.h中定义了类Student和函数fun。

//header1.h (头文件1,设其文件名为cc14-4-h1.h)

#include <string>

#include <cmath>

using namespace std;

class Student//声明Student类

{public:

   Student(int n,string nam,char s)

{num=n;name=nam;sex=s;}

   void get_data( );

private:

int num;

   string name;

   char sex;

 };

void Student::get_data( )               //成员函数定义

{cout<<num<<″ ″<<name<<″ ″<<sex<<endl;

}

double fun(double a,double b)          //定义全局函数(即外部函数)

{return sqrt(a+b);}

在main函数所在的文件中包含头文件header1.h:

#include <iostream>

#include ″cc14-4-h1.h″    //注意要用双引号,因为文件一般是放在用户目录中的

using namespace std;

int main( )

{Student stud1(101,″Wang″,18);  //定义类对象stud1

   stud1.get_data( );

   cout<<fun(5,3)<<endl;

   return 0;

   }

程序能正常运行,输出为

101 Wang 18

2.82843

如果程序员乙写了头文件header2.h,在其中除了定义其他类以外,还定义了类Student和函数fun,但其内容与头文件header1.h中的Student和函数fun有所不同。

//header2.h (头文件2,设其文件名为cc14-4-h2.h)

#include <string>

#include <cmath>

using namespace std;

class Student//声明Student类

{public:

   Student(int n,string nam,char s)      //参数与header1中的student不同

{num=n;name=nam;sex=s;}

   void get_data( );

private:

   int num;

   string name;

   char sex;                          //此项与header1不同

};

 

void Student::get_data( )               //成员函数定义

{cout<<num<<″ ″<<name<<″ ″<<sex<<endl;

}

double fun(double a,double b)        //定义全局函数

 {return sqrt(a-b);}                 //返回值与header1中的fun函数不同

//头文件2中可能还有其他内容

假如主程序员在其程序中要用到header1.h中的Student和函数fun,因而在程序中包含了头文件header1.h,同时要用到头文件header2.h中的一些内容,因而在程序中又包含了头文件header2.h。如果主文件(包含主函数的文件)如下:

//main file

#include <iostream>

#include ″cc14-4-h1.h″//包含头文件1

#include ″cc14-4-h2.h″        //包含头文件2

using namespace std;

int main( )

{Student stud1(101,″Wang″,18);

stud1.get_data();

cout<<fun(5,3)<<endl;

return 0;

 }

这时程序编译就会出错。 因为在预编译后,头文件中的内容取代了对应的#include命令行,这样就在同一个程序文件中出现了两个Student类和两个fun函数,显然是重复定义,这就是名字冲突,即在同一个作用域中有两个或多个同名的实体。

不仅如此,在程序中还往往需要引用一些库,为此需要包含有关的头文件。如果在这些库中包含有与程序的全局实体同名的实体,或者不同的库中有相同的实体名,则在编译时就会出现名字冲突。

为了避免这类问题的出现,人们提出了许多方法,例如: 将实体的名字写得长一些;把名字起得特殊一些,包括一些特殊的字符;由编译系统提供的内部全局标识符都用下划线作为前缀,如_complex(),以避免与用户命名的实体同名;由软件开发商提供的实体的名字用特定的字符作为前缀。但是这样的效果并不理想,而且增加了阅读程序的难度,可读性降低了。

C语言和早期的C++语言没有提供有效的机制来解决这个问题,没有使库的提供者能够建立自己的命名空间的工具。人们希望ANSI C++标准能够解决这个问题,提供一种机制、一种工具,使由库的设计者命名的全局标识符能够和程序的全局实体名以及其他库的全局标识符区别开来。

14.2.2 什么是命名空间

为了解决上面这个问题,ANSI C++增加了命名空间(namespace)。所谓命名空间,实际上就是一个由程序设计者命名的内存区域。程序设计者可以根据需要指定一些有名字的空间域,把一些全局实体分别放在各个命名空间中,从而与其他全局实体分隔开来。如

namespace ns1//指定命名空间ns1

{int a;

double b;

}

现在命名空间成员包括变量a和b,注意a和b仍然是全局变量,仅仅是把它们隐藏在指定的命名空间中而已。

如果在程序中要使用变量a和b,必须加上命名空间名和作用域分辨符“::”,如ns1::a,ns1::b。这种用法称为命名空间限定(qualified),这些名字(如ns1::a)称为被限定名(qualified name)。C++中命名空间的作用类似于操作系统中的目录和文件的关系。

命名空间的作用是建立一些互相分隔的作用域,把一些全局实体分隔开来,以免产生名字冲突。

可以根据需要设置许多个命名空间,每个命名空间名代表一个不同的命名空间域,不同的命名空间不能同名。这样,可以把不同的库中的实体放到不同的命名空间中。过去我们用的全局变量可以理解为全局命名空间,独立于所有有名的命名空间之外,它是不需要用namespace声明的,实际上是由系统隐式声明的,存在于每个程序之中。

在声明一个命名空间时,花括号内不仅可以包括变量,而且还可以包括以下类型:

变量(可以带有初始化);

常量;

函数(可以是定义或声明);

结构体;

类;

模板;

命名空间(在一个命名空间中又定义一个命名空间,即嵌套的命名空间)。

例如

namespace ns1

{const int RATE=0.08;//常量

double pay;                         //变量

double tax( )                        //函数

{return a*RATE;}

namespace ns2                       //嵌套的命名空间

    {int age;}

}

如果想输出命名空间ns1中成员的数据,可以采用下面的方法:

cout<<ns1::RATE<<endl;

cout<<ns1::pay<<endl;

cout<<ns1::tax()<<endl;

cout<<ns1::ns2::age<<endl;//需要指定外层的和内层的命名空间名

14.2.3 使用命名空间解决名字冲突

现在,对例14.4程序进行修改,使之能正确运行。

例14.5 利用命名空间来解决例14.4程序名字冲突问题。

修改两个头文件,把在头文件中声明的类分别放在两个不同的命名空间中。

//header1.h  (头文件1)

#include <string>

#include <cmath>

using namespace std;

namespace ns1//声明命名空间ns1

{class Student                 //在命名空间ns1内声明Student类

{public:

Student(int n,string nam,int a)

{num=n;name=nam;age=a;}

void get_data( );

     private:

int num;

string name;

int age;

    };

 void Student::get_data()     //定义成员函数

     {cout<<num<<″ ″<<name<<″ ″<<age<<endl;

     }

 

 double fun(double a,double b)  //在命名空间ns1内定义fun函数

    {return sqrt(a+b);}

}

 

//header2.h ((头文件2)

#include <string>

#include <cmath>

using namespace std;

namespace ns2                      //声明命名空间ns2

 {class Student

{public:

Student(int n,string nam,char s)

{num=n;name=nam;sex=s;}

void get_data( );

private:

int num;

char name[20];

char sex;

};

void Student::get_data( )

   {cout<<num<<″ ″<<name<<″ ″<<sex<<endl;

}

double fun(double a,double b)

{return sqrt(a-b);}

 }

//main file (主文件)

#include <iostream>

#include ″cc14-5-h1.h″          //包含头文件1

#include ″cc14-5-h2.h″          //包含头文件2

using namespace std;

int main( )

{ns1::Student stud1(101,″Wang″,18);  //用命名空间ns1中声明的Student类定义stud1

stud1.get_data( );                  //不要写成ns1::stud1.get_data( );

cout<<ns1::fun(5,3)<<endl;         //调用命名空间ns1中的fun函数

ns2::Student stud2(102,″Li″,′f′);  //用命名空间ns2中声明的Student类定义stud2

stud2.get_data( );

cout<<ns2::fun(5,3)<<endl;         //调用命名空间ns1中的fun函数

return 0;

 }

程序能顺利通过编译,并得到以下运行结果:

101 Wang 18(对象stud1中的数据)

2.82843               (5+3的开方值)

102 Li f              (对象stud2中的数据)

1.41421               (5-3的开方值)

14.2.4 使用命名空间成员的方法

在引用命名空间成员时,要用命名空间名和作用域分辨符对命名空间成员进行限定,以区别不同的命名空间中的同名标识符。即

命名空间名::命名空间成员名

这种方法是有效的,能保证所引用的实体有惟一的名字。但是如果命名空间名字比较长,尤其在有命名空间嵌套的情况下,为引用一个实体,需要写很长的名字。在一个程序中可能要多次引用命名空间成员,就会感到很不方便。

为此,C++提供了一些机制,能简化使用命名空间成员的手续。

(1) 使用命名空间别名

可以为命名空间起一个别名(namespace alias),用来代替较长的命名空间名。如

namespace Television//声明命名空间,名为Television

 {…}

可以用一个较短而易记的别名代替它。如

namespace TV = Television;//别名TV与原名Television等价

(2) 使用using 命名空间成员名

using后面的命名空间成员名必须是由命名空间限定的名字。例如

using ns1::Student;

using声明的有效范围是从using语句开始到using所在的作用域结束。如果在以上的using语句之后有以下语句: 

Student stud1(101,″Wang″,18);//此处的Student相当于ns1::Student

上面的语句相当于

ns1::Student stud1(101,″Wang″,18);

又如

using ns1::fun;//声明其后出现的fun是属于命名空间ns1中的fun

cout<<fun(5,3)<<endl;        //此处的fun函数相当于ns1::fun(5,3)

显然,这可以避免在每一次引用命名空间成员时都用命名空间限定,使得引用命名空间成员方便易用。

但是要注意: 在同一作用域中用using声明的不同命名空间的成员中不能有同名的成员。例如

using ns1::Student;//声明其后出现的Student是命名空间ns1中的Student

using ns2::Student;        //声明其后出现的Student是命名空间ns2中的Student

Student stud1;             //请问此处的Student是哪个命名空间中的Student?

产生了二义性,编译出错。

(3) 使用using namespace 命名空间名

能否在程序中用一个语句就能一次声明一个命名空间中的全部成员呢?

C++提供了using namespace语句来实现这一目的。using namespace语句的一般格式为

using namespace命名空间名;

例如

using namespace ns1;

声明了在本作用域中要用到命名空间ns1中的成员,在使用该命名空间的任何成员时都不必用命名空间限定。如果在作了上面的声明后有以下语句:

Student stud1(101,″Wang″,18);//Student隐含指命名空间ns1中的Student

cout<<fun(5,3)<<endl;          //这里的fun函数是命名空间ns1中的fun函数

在用using namespace声明的作用域中,命名空间ns1的成员就好像在全局域声明的一样。因此可以不必用命名空间限定。显然这样的处理对写程序比较方便。但是如果同时用using namespace声明多个命名空间时,往往容易出错。因此只有在使用命名空间数量很少,以及确保这些命名空间中没有同名成员时才用using namespace语句。

14.2.5 无名的命名空间

以上介绍的是有名字的命名空间,C++还允许使用没有名字的命名空间,如在文件A中声明了以下的无名命名空间:

namespace//命名空间没有名字

{void fun()                          //定义命名空间成员

    {cout<<″OK.″<<endl;}

}

由于命名空间没有名字,在其他文件中显然无法引用,它只在本文件的作用域内有效。无名命名空间的成员fun函数的作用域为文件A。在文件A中使用无名命名空间的成员,不必(也无法)用命名空间名限定。如果在文件A中有以下语句:

fun();

则执行无名命名空间中的成员fun函数,输出″OK.″。

在本程序中的其他文件中也无法使用该fun函数,也就是把fun函数的作用域限制在本文件范围中。

14.2.6 标准命名空间std

为了解决C++标准库中的标识符与程序中的全局标识符之间以及不同库中的标识符之间的同名冲突,应该将不同库的标识符在不同的命名空间中定义(或声明)。标准C++库的所有的标识符都是在一个名为std的命名空间中定义的,或者说标准头文件(如iostream)中函数、类、对象和类模板是在命名空间std中定义的。

这样,在程序中用到C++标准库时,需要使用std作为限定。如

std::cout<<″OK.″<<endl; //声明cout是在命名空间std中定义的流对象

在大多数的C++程序中常用using namespace语句对命名空间std进行声明,这样可以不必对每个命名空间成员一一进行处理,在文件的开头加入以下using namespace声明: 

using namespace std;

这样,在std中定义和声明的所有标识符在本文件中都可以作为全局量来使用。但是应当绝对保证在程序中不出现与命名空间std的成员同名的标识符。由于在命名空间std中定义的实体实在太多,有时程序设计人员也弄不清哪些标识符已在命名空间std中定义过,为减少出错机会,有的专业人员喜欢用若干个“using 命名空间成员” 声明来代替“using namespace 命名空间”声明,如

using std::string;

using std::cout;

using std::cin;

等。为了减少在每一个程序中都要重复书写以上的using声明,程序开发者往往把编写应用程序时经常会用到的命名空间std成员的using声明组成一个头文件,然后在程序中包含此头文件即可。

14.3 使用早期的函数库

C语言程序中各种功能基本上都是由函数来实现的,在C语言的发展过程中建立了功能丰富的函数库,C++从C语言继承了这份宝贵的财富。在C++程序中可以使用C语言的函数库。

如果要用函数库中的函数,就必须在程序文件中包含有关的头文件,在不同的头文件中,包含了不同的函数的声明。

在C++中使用这些头文件有两种方法。

(1) 用C语言的传统方法。头文件名包括后缀.h,如stdio.h,math.h等。由于C语言没有命名空间,头文件并不存放在命名空间中,因此在C++程序文件中如果用到带后缀.h的头文件时,不必用命名空间。只需在文件中包含所用的头文件即可。如

#include <math.h>

(2) 用C++的新方法。C++标准要求系统提供的头文件不包括后缀.h,例如iostream、string。为了表示与C语言的头文件有联系又有区别,C++所用的头文件名是在C语言的相应的头文件名(但不包括后缀.h)之前加一字母c。

此外,由于这些函数都是在命名空间std中声明的,因此在程序中要对命名空间std作声明。如

#include <cstdio>

#include <cmath>

using namespace std;

目前所用的大多数C++编译系统既保留了C的用法,又提供了C++的新方法。下面两种用法等价,可以任选。

C传统方法                         C++新方法

#include <stdio.h>                               #include <cstdio>

#include <math.h>                             #include <cmath>

#include <string.h>                        #include <cstring>

                                          using namespace std;

可以使用传统的C方法,但应当提倡使用C++的新方法。

 

 

#include <iostream>

using namespace std;

struct Date

  {int month;

   int day;

   int year;

  };

 struct Student

  {int num;

   char name[20];

   char sex;

   Date birthday;

   float score;

  }student1,student2={10002,"Wang Li",'f',5,23,1982,89.5};

 

int main()

{student1=student2;

 cout<<student1.num<<endl;

 cout<<student1.name<<endl;

 cout<<student1.sex<<endl;

 cout<<student1.birthday.month<<'/'<<student1.birthday.day<<'/';

 cout<<student1.birthday.year<<endl;

 cout<<student1.score<<endl;

 return 0;

}

 

#include <iostream>

#include <string>

using namespace std;

struct Person

 { char name[20];

   int count;

 };

int main()

 {Person leader[3]={"Li",0,"Zhang",0,"Fun",0};

  int i,j;

  char leader_name[20];

  for(i=0;i<10;i++)

    {cin>>leader_name;

     for(j=0;j<3;j++)

       if(strcmp(leader_name,leader[j].name)==0) leader[j].count++;

     }

  cout<<endl;

  for(i=0;i<3;i++)

    {cout<<leader[i].name<<":"<<leader[i].count<<endl;}

  return 0;

 }

#include <iostream>

#include <string>

using namespace std;

struct Person

 { string name;

   int count;

 };

int main()

 {Person leader[3]={"Li",0,"Zhang",0,"Fun",0};

  int i,j;

  string leader_name;

  for(i=0;i<3;i++)

    {cin>>leader_name;

     for(j=0;j<10;j++)

       if(leader_name==leader[j].name) leader[j].count++;

     }

  cout<<endl;

  for(i=0;i<3;i++)

    {cout<<leader[i].name<<":"<<leader[i].count<<endl;}

  return 0;

 }

 

#include <iostream>

#include <string>

using namespace std;

int main()

 {struct student

   {int num;

    string name;

    char sex;

    float score;

 };

 student stu;

 student *p=&stu;

 stu.num=10301;

 stu.name="Wang Fun";

 stu.sex='f';

 stu.score=89.5;

 cout<<(*p).num<<" "<<(*p).name<<" "<<(*p).sex<<" "<<(*p).score<<endl;

 cout<<p->num<<" "<<p->name<<" "<<p->sex<<" "<<(p->score<<endl;

 return 0;

}

 

#define NULL 0  

#include <iostream>

using namespace std;

struct Student

 {long num;

  float score;

  struct Student *next;

 };

int main()

{Student a,b,c,*head,*p;

 a.num=31001; a.score=89.5;

 b.num=31003; b.score=90;

 c.num=31007; c.score=85;

 head=&a;

 a.next=&b;

 b.next=&c;

 c.next=NULL;

 p=head;

 do       

   {cout<<p->num<<"  "<<p->score<<endl;

    p=p->next;

   } while(p!=NULL);

 return 0;

}

 

#include <iostream>

#include <string>

using namespace std;

struct Student

{int num;

 string name;

 float score[3];

};

int main()

{void print(Student);

 Student stu;

 stu.num=12345;

 stu.name="Li Fung";

 stu.score[0]=67.5;

 stu.score[1]=89;

 stu.score[2]=78.5;

 print(stu);

 return 0;

}

 

void print(Student stu)

{cout<<stu.num<<" "<<stu.name<<" "<<stu.score[0]<<" "

     <<stu.score[1]<<" "<<stu.score[2]<<endl;

}

#include <iostream>

#include <string>

using namespace std;

struct Student

{int num;

 string name;

 float score[3];

}stu={12345,"Li Fung",67.5,89,78.5};

 

int main()

{void print(Student *);

 Student *pt=&stu;

 print(pt);

 return 0;

}

 

void print(Student *p)

{cout<<p->num<<" "<<p->name<<" "<<p->score[0]<<" "

     <<p->score[1]<<" "<<p->score[2]<<endl;

}

#include <iostream>

#include <string>

using namespace std;

struct Student

{int num;

 string name;

 float score[3];

}stu={12345,"Li Fung",67.5,89,78.5};

 

int main()

{void print(Student &);

 print(stu);

 return 0;

}

 

void print(Student &stud)

{cout<<stud.num<<" "<<stud.name<<" "<<stud.score[0]<<" "<<stud.score[1]<<" "<<stud.score[2]<<endl;

}

 

#include <iostream>

#include <string>

using namespace std;

struct Student

{string name;

 int num;

 char sex;

};

int main ( )

{

 Student *p;

 p=new Student;

 p->name="Wang Fun";

 p->num=10123;

 p->sex='m';

 cout<<p->name<<endl<<p->num<<endl<<p->sex<<endl;

 delete p;

 return 0;

}

 

#include <iostream>

#include <string>

#include <iomanip>

using namespace std;

struct S

  {int num;

   string name;

   char sex;

   char job;

   union

     {int grade;

      char position[10];

     }category;

  }person[2];

 

int main()

{ int i;

  for(i=0;i<2;i++)

   {cin>>person[i].num>>person[i].name>>person[i].sex>>person[i].job;

    if(person[i].job=='s') cin>>person[i].category.grade;

    else if (person[i].job=='t') cin>>person[i].category.position;

        else cout<<"input error!";

   }

  cout<<endl<<"No.  Name   sex  job  grade/position"<<endl;

  for(i=0;i<2;i++)

    {if (person[i].job=='s')

      cout<<person[i].num<<setw(6)<<person[i].name<<"    "<<person[i].sex

      <<"    "<<person[i].job<<setw(10)<<person[i].category.grade<<endl;

     else

      cout<<person[i].num<<setw(6)<<person[i].name<<"    "<<person[i].sex

      <<"    "<<person[i].job<<setw(10)<<person[i].category.position<<endl;

    }

  return 0;

 }

 

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{enum color {red,yellow,blue,white,black};

 color pri;

 int i,j,k,n=0,loop;

 for (i=red;i<=black;i++)

   for (j=red;j<=black;j++)

     if (i!=j)

      { for (k=red;k<=black;k++)

        if ((k!=i) && (k!=j))

         {n=n+1;

          cout<<n;

          for (loop=1;loop<=3;loop++)

           {switch (loop)

             {case 1: pri=color(i);break;

              case 2: pri=color(j);break;

              case 3: pri=color(k);break;

              default:break;

             }

          switch (pri)

            {case red:    cout<<setw(8)<<"red"; break;

             case yellow: cout<<setw(8)<<"yellow"; break;

             case blue:   cout<<setw(8)<<"blue"; break;

             case white:  cout<<setw(8)<<"white"; break;

             case black:  cout<<setw(8)<<"black"; break;

             default   :                   break;

            }

         }

      cout<<endl;

     }

   }

   cout<<"total:"<<n<<endl;

   return 0;

}

 

#include <iostream>

using namespace std;

class Time

 {public:

  int hour;

  int minute;

  int sec;

 };

int main()

 { Time t1;

   Time &t2=t1;

   cin>>t2.hour;

   cin>>t2.minute;

   cin>>t1.sec;

   cout<<t1.hour<<":"<<t1.minute<<":"<<t2.sec<<endl;

 }

 

#include <iostream>

using namespace std;

class Time

 {public:

  int hour;

  int minute;

  int sec;

 };

int main()

 {Time t1;

  cin>>t1.hour;

  cin>>t1.minute;

  cin>>t1.sec;

  cout<<t1.hour<<":"<<t1.minute<<":"<<t1.sec<<endl;

  Time t2;

  cin>>t2.hour;

  cin>>t2.minute;

  cin>>t2.sec;

  cout<<t2.hour<<":"<<t2.minute<<":"<<t2.sec<<endl;

  return 0;

 }

 #include <iostream>

using namespace std;

class Time

 {public:

  int hour;

  int minute;

  int sec;

 };

int main()

 {

  void set_time(Time&) ;

  void show_time(Time&);

  Time t1;

  set_time(t1);

  show_time(t1);

  Time t2;

  set_time(t2);

  show_time(t2);

  return 0;

 }

 

void set_time(Time& t)

 {

  cin>>t.hour;

  cin>>t.minute;

  cin>>t.sec;

 }

 

void show_time(Time& t)

 {

  cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;

 }

 #include <iostream>

using namespace std;

class Time

 {public:

  int hour;

  int minute;

  int sec;

 };

int main()

 {

  void set_time(Time&,int hour=0,int minute=0,int sec=0);

  void show_time(Time&);

  Time t1;

  set_time(t1,12,23,34);

  show_time(t1);

  Time t2;

  set_time(t2);

  show_time(t2);

  return 0;

 }

 

void set_time(Time& t,int hour=9,int minute=30,int sec=0)

 {

  t.hour=hour;

  t.minute=minute;

  t.sec=sec;

 }

 

void show_time(Time& t)

 {

  cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;

 }

 

#include <iostream>

using namespace std;

class Time

 {public:

   void set_time() ;

   void show_time();

  private:

   int hour;

   int minute;

   int sec;

 };

int main()

 {

  Time t1;

  t1.set_time();

  t1.show_time();

  Time t2;

  t2.set_time();

  t2.show_time();

  return 0;

 }

 

void Time::set_time()

 {

  cin>>hour;

  cin>>minute;

  cin>>sec;

 }

 

void Time::show_time()

 {

  cout<<hour<<":"<<minute<<":"<<sec<<endl;

 }

 

#include <iostream>

using namespace std;

class Array_max

{public:

   void set_value();

   void max_value();

   void show_value();

 private:

   int array[10];

   int max;

};

 

void Array_max::set_value()

 { int i;

   for (i=0;i<10;i++)

     cin>>array[i];

 }

 

void Array_max::max_value()

 {int i;

  max=array[0];

  for (i=1;i<10;i++)

   if(array[i]>max) max=array[i];

  }

 

void Array_max::show_value()

 {cout<<"max="<<max;

 }

 

int main()

 {Array_max  arrmax;

  arrmax.set_value();

  arrmax.max_value();

  arrmax.show_value();

  return 0;

 }

 

//main.cpp

#include <iostream>

#include "student.h"

int main()

{Student stud;

 stud.display();

 return 0;

}

//student.cpp                            这是源文件,在此文件中进行函数的定义

#include <iostream>

#include "student.h"                    //不要漏写此行

void Student::display( )                 //在类外定义display类函数

{cout<<"num:"<<num<<endl;

 cout<<"name:"<<name<<endl;

 cout<<"sex:"<<sex<<endl;

}

//student.h                           

class Student               //类定义       

{ public:

    void display( );           //公用成员函数原型声明

  private:

    int num;

    char name[20];

    char sex ;

  };

 

#include <iostream>

using namespace std;

class Time

 {public:

   Time()

   {hour=0;

    minute=0;

    sec=0;

   } 

   void set_time();

   void show_time();

  private:

   int hour;

   int minute;

   int sec;

 };

 

void Time::set_time()

{cin>>hour;

 cin>>minute;

 cin>>sec;

}

 

void Time::show_time()

 {

  cout<<hour<<":"<<minute<<":"<<sec<<endl;

 }

 

int main()

 {

  Time t1;

  t1.show_time();

  Time t2;

  t2.show_time();

  return 0;

 }

 

#include <iostream>

using namespace std;

class Time

 {public:

  //构造函数重载

   Time();    //无参构造函数

   Time(int,int);   //有参构造函数  

   Time(int h,int m,int s):hour(h),minute(m),sec(s){}  //参数初始化表

   void show_time();

  private:

   int hour;

   int minute;

   int sec;

 };

Time::Time()

{   hour=0;

    minute=0;

    sec=0;

}

Time::Time(int h,int m)

{   hour=h;

    minute=m;

    sec=0;

}

 

void Time::show_time()

{

  cout<<hour<<":"<<minute<<":"<<sec<<endl;

}

 

int main()

 {

  Time t1;

  t1.show_time();

  Time t2(12,5);

  t2.show_time();

  Time t3(1,5,30);

  t3.show_time();

  return 0;

 }

#include <iostream>

using namespace std;

 

class Time

 {public:

   Time();

   void show_time();

  private:

   int hour;

   int minute;

   int sec;

 };

 

Time::Time()

 {

  hour=0;

  minute=0;

  sec=0;

 }

 

int main()

 {

  Time t1;

  t1.show_time();

  Time t2;

  t2.show_time();

  return 0;

 }

 

void Time::show_time()

 {

  cout<<hour<<":"<<minute<<":"<<sec<<endl;

 }

 

#include <iostream>

using namespace std;

class Box

 {public:

   Box(int,int,int);

   int volume();

  private:

   int height;

   int width;

   int length;

 };

Box::Box(int h,int w,int len)

 {height=h;

  width=w;

  length=len;

 }

 

int Box::volume()

 {return(height*width*length);

 }

 

   

int main()

 {

  Box box1(12,25,30);

  cout<<"The volume of box1 is "<<box1.volume()<<endl;

  Box box2(15,30,21);

  cout<<"The volume of box2 is "<<box2.volume()<<endl;

  return 0;

 }

 

#include <iostream>

using namespace std;

class Box

 {public:

   Box();                 

   Box(int h,int w ,int len):height(h),width(w),length(len){}

   int volume();

  private:

   int height;

   int width;

   int length;

 };

Box::Box()                

 {height=10;

  width=10;

  length=10;

 }

 

int Box::volume()

 {return(height*width*length);

 }

   

int main()

 {

  Box box1;                                   

  cout<<"The volume of box1 is "<<box1.volume()<<endl;

  Box box2(15,30,25);                         

  cout<<"The volume of box2 is "<<box2.volume()<<endl;

  return 0;

 }

 

#include <iostream>

using namespace std;

class Box

 {public:

   Box(int w=10,int h=10,int len=10);

   int volume();

  private:

   int height;

   int width;

   int length;

 };

 

Box::Box(int w,int h,int len)

 {height=h;

  width=w;

  length=len;

 }

 

int Box::volume()

 {return(height*width*length);

 }

 

   

int main()

 {

  Box box1;

  cout<<"The volume of box1 is "<<box1.volume()<<endl;

  Box box2(15);

  cout<<"The volume of box2 is "<<box2.volume()<<endl;

  Box box3(15,30);

  cout<<"The volume of box3 is "<<box3.volume()<<endl;

  Box box4(15,30,20);

  cout<<"The volume of box4 is "<<box4.volume()<<endl;

  return 0;

 }

 

 #include <iostream>

using namespace std;

class Box

 {public:

   Box(int=10,int=10,int=10);

   int volume();

  private:

   int height;

   int width;

   int length;

 };

 

Box::Box(int h,int w,int len):height(h),width(w),length(len)

{ }

 

int Box::volume()

 {return(height*width*length);

 }

 

   

int main()

 {

  Box box1;

  cout<<"The volume of box1 is "<<box1.volume()<<endl;

  Box box2(15);

  cout<<"The volume of box2 is "<<box2.volume()<<endl;

  Box box3(15,30);

  cout<<"The volume of box3 is "<<box3.volume()<<endl;

  Box box4(15,30,20);

  cout<<"The volume of box4 is "<<box4.volume()<<endl;

  return 0;

 }

 

 #include <iostream>

#include <string>

using namespace std;

class Student

 {public:

   Student(int n,string nam,char s)

    {num=n;

     name=nam;

     sex=s;

     cout<<"Constructor called."<<endl;

    }

   ~Student()

   {cout<<"Destructor called."<<endl;}

   void display()

   {cout<<"num:"<<num<<endl;

    cout<<"name:"<<name<<endl;

       cout<<"sex:"<<sex<<endl<<endl;

   }

  private:

    int num;

    string name;

    char sex;

};

 

int main()

  {Student stud1(10010,"Wang_li",'f');

   stud1.display();

   Student stud2(10011,"Zhang_fun",'m');

   stud2.display();

   return 0;

}

 

#include <iostream>

using namespace std;

 

class Box

 {public:

   Box(int h=10,int w=12,int len=15):height(h),width(w),length(len){ }

   int volume();

  private:

   int height;

   int width;

   int length;

 };

 

int Box::volume()

 {return(height*width*length);

 }

   

int main()

 {

  Box a[3]={

   Box(10,12,15),

   Box(15,18,20),

   Box(16,20,26)

   };

  cout<<"volume of a[0] is "<<a[0].volume()<<endl;

  cout<<"volume of a[0] is "<<a[1].volume()<<endl;

  cout<<"volume of a[0] is "<<a[2].volume()<<endl;

  return 0;

 }

 

#include <iostream>

using namespace std;

 class Time

 {public:

   Time(int,int,int);

   int hour;

   int minute;

   int sec;

   void get_time();

 };

 Time::Time(int h,int m,int s)

 {hour=h;

  minute=m;

  sec=s;

 }

void Time::get_time()

   {cout<<hour<<":"<<minute<<":"<<sec<<endl;}

 

int main()

 {Time t1(10,13,56);

  int *p1=&t1.hour;

  cout<<*p1<<endl;

  t1.get_time();

  Time *p2=&t1;

  p2->get_time();

  void (Time::*p3)();

  p3=&Time::get_time;

  (t1.*p3)();

  return 0;

}

 

 #include <iostream>

using namespace std;

class Time

 {public:

   Time(int,int,int);

   int hour;

   int minute;

   int sec;

 };

 Time::Time(int h,int m,int s)

 {hour=h;

  minute=m;

  sec=s;

 }

 

void fun(Time &t)

{t.hour=18;}

 

int main()

{Time t1(10,13,56);

 fun(t1);

 cout<<t1.hour<<endl;

 return 0;

}

 

 

#include <iostream>

using namespace std;

class Box

 {public:

   Box(int=10,int=10,int=10);              

   int volume();

  private:

   int height;

   int width;

   int length;

 };

 

Box::Box(int h,int w,int len)

 {height=h;

  width=w;

  length=len;

 }

 

int Box::volume()

 {return(height*width*length);     

 }

    

int main()

 {

  Box box1(15,30,25),box2;                      

  cout<<"The volume of box1 is "<<box1.volume()<<endl;

  box2=box1;                                  

  cout<<"The volume of box2 is "<<box2.volume()<<endl;

  return 0;

 }

#include <iostream>

using namespace std;

 

class Box

 {public:

   Box(int=10,int=10,int=10);

   int volume();

  private:

   int height;

   int width;

   int length;

 };

 

Box::Box(int h,int w,int len)

 {height=h;

  width=w;

  length=len;

 }

int Box::volume()

 {return(height*width*length);

 }

 

   

int main()

 {Box box1(15,30,25);

  cout<<"The volume of box1 is "<<box1.volume()<<endl;

  Box box2=box1,box3=box2;

  cout<<"The volume of box2 is "<<box2.volume()<<endl;

  cout<<"The volume of box3 is "<<box3.volume()<<endl;

  return 0;

 

 }

 

#include <iostream>

using namespace std;

 

class Box

 {public:

   Box(int,int);

   int volume();

   static int height;

   int width;

   int length;

 };

 

Box::Box(int w,int len)

 {

  width=w;

  length=len;

 }

int Box::volume()

 {return(height*width*length);

 }

int Box::height=10;

 

int main()

 {

  Box a(15,20),b(20,30);

 
cout<<a.height<<endl;

  cout<<b.height<<endl;

  cout<<Box::height<<endl;

  cout<<a.volume()<<endl;

  return 0;

 }

 

#include <iostream>

using namespace std;

class Student

 {public:

   Student(int,int,int);

   void total();

   static float average();

  private:

   int num;

   int age;

   float score;

   static float sum;

   static int count;

 };

 

 Student::Student(int m,int a,int s)

 {num=m;

  age=a;

  score=s;

 }

 

void Student::total()

   {

    sum+=score;

    count++;

   }

  

float  Student::average()

 { return(sum/count);

 }

 

float Student::sum=0;

int Student::count=0;

 

int main()

 {

   Student stud[3]={

     Student(1001,18,70),

     Student(1002,19,79),

     Student(1005,20,98)

    };

   int n;

   cout<<"please input the number of students:";

   cin>>n;

   for(int i=0;i<n;i++)

     stud[i].total();

   cout<<"The average score of "<<n<<" students is "<<stud[0].average()<<endl;

   return 0;

 }

 

#include <iostream>

using namespace std;

 

class Time

 {public:

   Time(int,int,int);

   friend void display(Time &);

  private:

   int hour;

   int minute;

   int sec;

 };

 Time::Time(int h,int m,int s)

 {hour=h;

  minute=m;

  sec=s;

 }

void display(Time &t)

 {

  cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;

 }

  

int main()

{

 Time t1(10,13,56);

 display(t1);

 return 0;

}

 

#include <iostream>

using namespace std;

class Date;

class Time

 {public:

   Time(int,int,int);

   void display(const Date&);

  private:

   int hour;

   int minute;

   int sec;

 };

 

 class Date

 {public:

   Date(int,int,int);

   friend void Time::display(const Date &);

  private:

   int month;

   int day;

   int year;

 };

 

 Time::Time(int h,int m,int s)

 {hour=h;

  minute=m;

  sec=s;

 }

 

void Time::display(const Date &da)

 {cout<<da.month<<"/"<<da.day<<"/"<<da.year<<endl;

  cout<<hour<<":"<<minute<<":"<<sec<<endl;

 }

 

 

Date::Date(int m,int d,int y)

 {month=m;

  day=d;

  year=y;

 }

  

int main()

{Time t1(10,13,56);

 Date d1(12,25,2004);

 t1.display(d1);

 return 0;

}

 

#include <iostream>

using namespace std;

template<class numtype>

class Compare

 {public:

   Compare(numtype a,numtype b)

    {x=a;y=b;}

   numtype max()

    {return (x>y)?x:y;}

   numtype min()

    {return (x<y)?x:y;}

  private:

    numtype x,y;

 };

int main()

{Compare<int> cmp1(3,7);

 cout<<cmp1.max()<<" is the Maximum of two inteder numbers."<<endl;

 cout<<cmp1.min()<<" is the Minimum of two inteder numbers."<<endl<<endl;

 Compare<float> cmp2(45.78,93.6);

 cout<<cmp2.max()<<" is the Maximum of two float numbers."<<endl;

 cout<<cmp2.min()<<" is the Minimum of two float numbers."<<endl<<endl;

 Compare<char> cmp3('a','A');

 cout<<cmp3.max()<<" is the Maximum of two characters."<<endl;

 cout<<cmp3.min()<<" is the Minimum of two characters."<<endl;

 return 0;

}

 

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   Complex complex_add(Complex &c2);

   void display();

  private:

   double real;

   double imag;

 };

Complex Complex::complex_add(Complex &c2)

{return Complex(real+c2.real,imag+c2.imag);}

  

void Complex::display()

{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

 

int main()

{Complex c1(3,4),c2(5,-10),c3;

 c3=c1.complex_add(c2);

 cout<<"c1="; c1.display();

 cout<<"c2="; c2.display();

 cout<<"c1+c2="; c3.display();

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   Complex operator + (Complex &c2);

   void display();

  private:

   double real;

   double imag;

 };

Complex Complex::operator + (Complex &c2)

{Complex c;

 c.real=real+c2.real;

 c.imag=imag+c2.imag;

return c;}

  

void Complex::display()

{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

 

int main()

{Complex c1(3,4),c2(5,-10),c3;

 c3=c1+c2;

 cout<<"c1=";c1.display();

 cout<<"c2=";c2.display();

 cout<<"c1+c2=";c3.display();

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   Complex operator + (Complex &c2);

   void display();

  private:

   double real;

   double imag;

 };

Complex Complex::operator + (Complex &c2)

 {return Complex(real+c2.real,imag+c2.imag);}

  

void Complex::display()

{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

 

int main()

{Complex c1(3,4),c2(5,-10),c3;

 c3=c1+c2;

 cout<<"c1="; c1.display();

 cout<<"c2="; c2.display();

 cout<<"c1+c2="; c3.display();

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r){real=r;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   friend Complex operator+ (Complex &c1,Complex &c2);

   void display();

  private:

   double real;

   double imag;

 };

 

Complex operator+ (Complex &c1,Complex &c2)

 {return Complex(c1.real+c2.real, c1.imag+c2.imag);}

  

void Complex::display()

{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

 

int main()

{Complex c1(3,4),c2(5,-10),c3;

 c3=c1+c2;

 cout<<"c1="; c1.display();

 cout<<"c2="; c2.display();

 cout<<"c1+c2="; c3.display();

 return 0;

}

#include <iostream>

using namespace std;

class String           //String 是用户自己指定的类名

 {public:

   String(){p=NULL;}

   String(char *str);

   void display();

  private:

   char *p;

 };

 

String::String(char *str)

  {p=str;}

 

void String::display()

  {cout<<p;}

 

int main()

  {String string1("Hello"),string2("Book");

   string1.display();

   cout<<endl;

   string2.display();

   return 0;

}

//本程序适用于VC++ 6.0

#include <iostream.h>

#include <string.h>

class String

 {public:

   String(){p=NULL;}

   String(char *str);

   friend bool operator>(String &string1,String &string2);

   friend bool operator<(String &string1,String &string2);

   friend bool operator==(String &string1,String &string2);

   void display();

  private:

   char *p;

 };

 

String::String(char *str)

  {p=str;}

 

void String::display()

{cout<<p;}

 

 

bool operator>(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)>0)

    return true;

   else return false;

  }

 

int main()

{String string1("Hello"),string2("Book");

 cout<<(string1>string2)<<endl;

 return 0;

}

#include <iostream>

#include <cstring>

using namespace std;

class String

 {public:

   String(){p=NULL;}

   String(char *str);

   friend bool operator>(String &string1,String &string2);

   friend bool operator<(String &string1,String &string2);

   friend bool operator==(String &string1,String &string2);

   void display();

  private:

   char *p;

 };

 

String::String(char *str)

  {p=str;}

 

void String::display()

{cout<<p;}

 

 

bool operator>(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)>0)

    return true;

   else return false;

  }

 

int main()

{String string1("Hello"),string2("Book");

 cout<<(string1>string2)<<endl;

 return 0;

}

//本程序适用于VC++ 6.0

#include <iostream.h>

#include <string.h>

class String

 {public:

   String(){p=NULL;}

   String(char *str);

   friend bool operator>(String &string1,String &string2);

   friend bool operator<(String &string1,String &string2);

   friend bool operator==(String &string1,String &string2);

   void display();

  private:

   char *p;

 };

 

String::String(char *str)

  {p=str;}

 

void String::display()

{cout<<p;}

 

bool operator>(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)>0)

    return true;

   else

    return false;

  }

 

bool operator<(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)<0)

    return true;

   else

    return false;

  }

 

bool operator==(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)==0)

    return true;

   else

    return false;

  }

 

int main()

{String string1("Hello"),string2("Book"),string3("Computer");

 cout<<(string1>string2)<<endl;

 cout<<(string1<string3)<<endl;

 cout<<(string1==string2)<<endl;

 return 0;

}

#include <iostream>

#include <string>

using namespace std;

class String

 {public:

   String(){p=NULL;}

   String(char *str);

   friend bool operator>(String &string1,String &string2);

   friend bool operator<(String &string1,String &string2);

   friend bool operator==(String &string1,String &string2);

   void display();

  private:

   char *p;

 };

 

String::String(char *str)

  {p=str;}

 

void String::display()

{cout<<p;}

 

bool operator>(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)>0)

    return true;

   else

    return false;

  }

 

bool operator<(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)<0)

    return true;

   else

    return false;

  }

 

bool operator==(String &string1,String &string2)

  {if(strcmp(string1.p,string2.p)==0)

    return true;

   else

    return false;

  }

 

int main()

{String string1("Hello"),string2("Book"),string3("Computer");

 cout<<(string1>string2)<<endl;

 cout<<(string1<string3)<<endl;

 cout<<(string1==string2)<<endl;

 return 0;

}

//本程序适用于VC++ 6.0

#include <iostream.h>

#include <string.h>

class String

 {public:

   String(){p=NULL;}

   String(char *str);

   friend bool operator>(String &string1,String &string2);

   friend bool operator<(String &string1,String &string2);

   friend bool operator==(String &string1,String &string2);

  void display();

  private:

   char *p;

 };

 

String::String(char *str)

{p=str;

}

 

void String::display()

 {cout<<p;}

 

bool operator>(String &string1,String &string2)

{if(strcmp(string1.p,string2.p)>0)

   return true;

 else

   return false;

}

 

bool operator<(String &string1,String &string2)

{if(strcmp(string1.p,string2.p)<0)

   return true;

 else

   return false;

}

 

bool operator==(String &string1,String &string2)

{if(strcmp(string1.p,string2.p)==0)

   return true;

 else

   return false;

}

 

void compare(String &string1,String &string2)

{if(operator>(string1,string2)==1)

  {string1.display();cout<<">";string2.display();}

 else

  if(operator<(string1,string2)==1)

   {string1.display();cout<<"<";string2.display();}

 else

  if(operator==(string1,string2)==1)

   {string1.display();cout<<"=";string2.display();}

 cout<<endl;

}

 

int main()

{String string1("Hello"),string2("Book"),string3("Computer"),string4("Hello");

 compare(string1,string2);

 compare(string2,string3);

 compare(string1,string4);

 return 0;

}

#include <iostream>

#include <cstring>

using namespace std;

class String

 {public:

   String(){p=NULL;}

   String(char *str);

   friend bool operator>(String &string1,String &string2);

   friend bool operator<(String &string1,String &string2);

   friend bool operator==(String &string1,String &string2);

  void display();

  private:

   char *p;

 };

 

String::String(char *str)

{p=str;

}

 

void String::display()

 {cout<<p;}

 

bool operator>(String &string1,String &string2)

{if(strcmp(string1.p,string2.p)>0)

   return true;

 else

   return false;

}

 

bool operator<(String &string1,String &string2)

{if(strcmp(string1.p,string2.p)<0)

   return true;

 else

   return false;

}

 

bool operator==(String &string1,String &string2)

{if(strcmp(string1.p,string2.p)==0)

   return true;

 else

   return false;

}

 

void compare(String &string1,String &string2)

{if(operator>(string1,string2)==1)

  {string1.display();cout<<">";string2.display();}

 else

  if(operator<(string1,string2)==1)

   {string1.display();cout<<"<";string2.display();}

 else

  if(operator==(string1,string2)==1)

   {string1.display();cout<<"=";string2.display();}

 cout<<endl;

}

 

int main()

{String string1("Hello"),string2("Book"),string3("Computer"),string4("Hello");

 compare(string1,string2);

 compare(string2,string3);

 compare(string1,string4);

 return 0;

}

#include <iostream>

using namespace std;

class Time

{public:

   Time(){minute=0;sec=0;}

   Time(int m,int s):minute(m),sec(s){}

   Time operator++();

   void display(){cout<<minute<<":"<<sec<<endl;}

  private:

   int minute;

   int sec;

 };

 

Time Time::operator++()

{if(++sec>=60)

  {sec-=60;

   ++minute;}

   return *this;

}

  

int main()

{Time time1(34,0);

 for (int i=0;i<61;i++)

       {++time1;

     time1.display();}

 return 0;

}

#include <iostream>

using namespace std;

class Time

{public:

   Time(){minute=0;sec=0;}

   Time(int m,int s):minute(m),sec(s){}

   Time operator++();

   Time operator++(int);

   void display(){cout<<minute<<":"<<sec<<endl;}

  private:

   int minute;

   int sec;

 };

 

 

Time Time::operator++()

{if(++sec>=60)

  {sec-=60;

   ++minute;}

 return *this;

}

Time Time::operator++(int)

{Time temp(*this);

 sec++;

 if(sec>=60)

  {sec-=60;

   ++minute;}

 return temp;

}

 

  

int main()

{Time time1(34,59),time2;

 cout<<" time1 : ";

 time1.display();

 ++time1;

 cout<<"++time1: ";

 time1.display();

 time2=time1++;

 cout<<"time1++: ";

 time1.display();

 cout<<" time2 : ";

 time2.display();

 return 0;

}

//本程序适用于VC++ 6.0

#include <iostream.h>         

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   Complex operator + (Complex &c2);

   friend ostream& operator << (ostream&,Complex&);

  private:

   double real;

   double imag;

 };

Complex Complex::operator + (Complex &c2)

 {return Complex(real+c2.real,imag+c2.imag);}

  

ostream& operator << (ostream& output,Complex& c)

{output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;

 return output;

}

 

int  main()

{Complex c1(2,4),c2(6,10),c3;

 c3=c1+c2;

 cout<<c3;

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   Complex operator + (Complex &c2);

   friend ostream& operator << (ostream&,Complex&);

  private:

   double real;

   double imag;

 };

Complex Complex::operator + (Complex &c2)

 {return Complex(real+c2.real,imag+c2.imag);}

  

ostream& operator << (ostream& output,Complex& c)

{output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;

 return output;

}

 

int  main()

{Complex c1(2,4),c2(6,10),c3;

 c3=c1+c2;

 cout<<c3;

 return 0;

}

//本程序适用于VC++ 6.0

#include <iostream.h>

class Complex

 {public:

   friend ostream& operator << (ostream&,Complex&);

   friend istream& operator >> (istream&,Complex&);

  private:

   double real;

   double imag;

 };

  

ostream& operator << (ostream& output,Complex& c)

{output<<"("<<c.real;

 if(c.imag>=0) output<<"+";

 output<<c.imag<<"i)";

 return output;

}

 

istream& operator >> (istream& input,Complex& c)

{cout<<"input real part and imaginary part of complex number:";

 input>>c.real>>c.imag;

 return input;

}

 

int main()

{Complex c1,c2;

 cin>>c1>>c2;

 cout<<"c1="<<c1<<endl;

 cout<<"c2="<<c2<<endl;

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   friend ostream& operator << (ostream&,Complex&);

   friend istream& operator >> (istream&,Complex&);

  private:

   double real;

   double imag;

 };

  

ostream& operator << (ostream& output,Complex& c)

{output<<"("<<c.real<<"+"<<c.imag<<"i)";

 return output;

}

 

istream& operator >> (istream& input,Complex& c)

{cout<<"input real part and imaginary part of complex number:";

 input>>c.real>>c.imag;

 return input;

}

 

 

int main()

{Complex c1,c2;

 cin>>c1>>c2;

 cout<<"c1="<<c1<<endl;

 cout<<"c2="<<c2<<endl;

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   operator double() {return real;}   

  private:

   double real;

   double imag;

 };

 

int main()

{Complex c1(3,4),c2(5,-10),c3;

 double d;

 d=2.5+c1;

 cout<<d<<endl;

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r){real=r;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   friend Complex operator + (Complex c1,Complex c2);

   void display();

  private:

   double real;

   double imag;

 };

 

Complex operator + (Complex c1,Complex c2)

 {return Complex(c1.real+c2.real, c1.imag+c2.imag);}

  

void Complex::display()

{cout<<"("<<real<<"+"<<imag<<"i)"<<endl;}

 

int main()

{Complex c1(3,4),c2(5,-10),c3;

 c3=c1+2.5;

 c3.display();

 return 0;

}

#include <iostream>

using namespace std;

class Complex

 {public:

   Complex(){real=0;imag=0;}

   Complex(double r){real=r;imag=0;}

   Complex(double r,double i){real=r;imag=i;}

   operator double(){cout<<return real;}

   friend Complex operator + (Complex c1,Complex c2);               

   void display();

  private:

   double real;

   double imag;

 };

 

Complex operator + (Complex c1,Complex c2)

 {return Complex(c1.real+c2.real, c1.imag+c2.imag);}

  

void Complex::display()

{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

 

int main()

{Complex c1(3,4),c2(5,-10),c3;

 c3=c1+2.5;

 c3.display();

 return 0;

}

#include <iostream>

#include <string>

using namespace std;

class Student

{public:

  void get_value()

   {cin>>num>>name>>sex;}

  void display( )

    {cout<<"num: "<<num<<endl;

     cout<<"name: "<<name<<endl;

     cout<<"sex: "<<sex<<endl;}

 private :

   int num;

   string name;

   char sex;

};  

 

class Student1: public Student

 {public:

   void get_value_1()

    {cin>>age>>addr;}

   void display_1()

    {  //cout<<"num: "<<num<<endl;        //企图引用基类的私有成员,错误

       //cout<<"name: "<<name<<endl;      //企图引用基类的私有成员,错误

       //cout<<"sex: "<<sex<<endl;        //企图引用基类的私有成员,错误

       cout<<"age: "<<age<<endl;          //引用派生类的私有成员,正确

       cout<<"address: "<<addr<<endl;}    //引用派生类的私有成员,正确

  private:

       int age;

       string addr;

 };

 

int main()

 {Student1 stud1;

  stud1.get_value();

  stud1.get_value_1();

  stud1.display();

  stud1.display_1();

  return 0;

}

#include <iostream>

#include <string>

using namespace std;

class Student

{public:

  void display( )

    {cout<<"num: "<<num<<endl;

     cout<<"name: "<<name<<endl;

     cout<<"sex: "<<sex<<endl;}

 private :

   int num;

   string name;

   char sex;

};  

 

class Student1: private Student

 {public:

   void display_1()

       {display();

       cout<<"age: "<<age<<endl;          //引用派生类的私有成员,正确

       cout<<"address: "<<addr<<endl;}    //引用派生类的私有成员,正确

  private:

       int age;

       string addr;

 };

 

int main()

 {Student1 stud1;

  stud1.display_1();

  return 0;

}

#include <iostream>

#include <string>

using namespace std;

class Student                        //声明基类

{public:                             //基类公用成员               

  void display( );

 protected :                         //基类保护成员

    int num;

    string name;

    char sex;

};

 

void Student::display( )

   {cout<<"num: "<<num<<endl;

    cout<<"name: "<<name<<endl;

    cout<<"sex: "<<sex<<endl;

   }

  

class Student1: protected Student     //用protected继承方式声明一个派生类

{public:

   void display1( );

 private:

   int age;                          

   string addr;

};

 

void Student1::display1( )

    {cout<<"num: "<<num<<endl;         //引用基类的保护成员,合法

     cout<<"name: "<<name<<endl;       //引用基类的保护成员,合法

     cout<<"sex: "<<sex<<endl;         //引用基类的保护成员,合法

     cout<<"age: "<<age<<endl;         //引用派生类的私有成员,合法

     cout<<"address: "<<addr<<endl;    //引用派生类的私有成员,合法

  

 

int main( )

 {Student1 stud1;                      //stud2是派生类student2的对象

  stud1.display1( );                  //display是派生类中的公用成员函数

  return 0;

 }

#include <iostream>

#include<string>

using namespace std;

class Student                              //声明基类

 {public:                                  //公用部分

   Student(int n,string nam,char s )       //基类构造函数

    {num=n;

     name=nam;

     sex=s; }

   ~Student( ) { }

  protected:                               //保护部分

    int num;

    string name;

    char sex ;                            //基类析构函数

};

 

class Student1: public Student                   //声明公用派生类student

 {public:

   Student1(int n,string nam,char s,int a,char ad[]) : Student(n,nam,s),age(a)

                                             //派生类构造函数

    {age=a;                          //在函数体中只对派生类新增的数据成员初始化

     addr=ad;

    }

   void show( )

    {cout<<"num: "<<num<<endl;

     cout<<"name: "<<name<<endl;

     cout<<"sex: "<<sex<<endl;

     cout<<"age: "<<age<<endl;

     cout<<"address: "<<addr<<endl<<endl;

    }

   ~Student1( ) { }                      //派生类析构函数

  private:                               //派生类的私有部分

   int age;                         

   string addr;               

 };

 

int main( )

 {Student1 stud1(10010,"Wang-li",'f',19,"115 Beijing Road,Shanghai");

  Student1 stud2(10011,"Zhang-fun",'m',21,"213 Shanghai Road,Beijing");

  stud1.show( );            //输出第一个学生的数据

  stud2.show( );            //输出第二个学生的数据

  return 0;

}

#include <iostream>

#include <string>

using namespace std;

class Student                              //声明基类

 {public:                                  //公用部分

   Student(int n,string nam)              //基类构造函数

    {num=n;

     name=nam;

    }

   void display()                           //输出基类数据成员

    {cout<<"num:"<<num<<endl<<"name:"<<name<<endl;}

  protected:                                //保护部分

    int num;

    string name;

};

 

class Student1: public Student              //用public继承方式声明派生类student

 {public:

   Student1(int n,string nam,int n1,string nam1,int a,string ad)

      :Student(n,nam),monitor(n1,nam1)               //派生类构造函数

    {age=a;                                 //在此处只对派生类新增的数据成员初始化

     addr=ad;

    }

   void show( )

    {cout<<"This student is:"<<endl;

     display();                               //输出num和name

     cout<<"age: "<<age<<endl;

     cout<<"address: "<<addr<<endl<<endl;

    }

   

   void show_monitor()                        //输出子对象的数据成员

    {cout<<endl<<"Class monitor is:"<<endl;

     monitor.display();                       //调用基类成员函数

    }

   private:                                //派生类的私有数据

    Student monitor;                       //定义子对象(班长)

    int age;

    string addr;               

  };

 

int main( )

 {Student1 stud1(10010,"Wang-li",10001,"Li-sun",19,"115 Beijing Road,Shanghai");

  stud1.show( );                             //输出第一个学生的数据

  stud1.show_monitor();                       //输出子对象的数据

  return 0;

 }

#include <iostream>

#include<string>

using namespace std;

class Student                              //声明基类

 {public:                                  //公用部分

   Student(int n, string nam )            //基类构造函数

    {num=n;

     name=nam;

    }

   void display()                           //输出基类数据成员

    {cout<<"num:"<<num<<endl;

     cout<<"name:"<<name<<endl;

    }

  protected:                                //保护部分

    int num;                                //基类有两个数据成员

    string name;

};

 

class Student1: public Student               //声明公用派生类Student1

 {public:

   Student1(int n,char nam[10],int a):Student(n,nam)        //派生类构造函数

    {age=a; }                         //在此处只对派生类新增的数据成员初始化

   void show( )                               //输出num,name和age

    {display();                               //输出num和name

     cout<<"age: "<<age<<endl;

    }

   private:                                   //派生类的私有数据

    int age;                                  //增加一个数据成员

  };

 

class Student2:public Student1               //声明间接公用派生类student2

 {public:

   //下面是间接派生类构造函数

   Student2(int n, string nam,int a,int s):Student1(n,nam,a)

    {score=s;}

   void show_all()                              //输出全部数据成员

    {show();                                    //输出num和name

     cout<<"score:"<<score<<endl;               //输出age

    }

  private:

   int score;                                   //增加一个数据成员

 };

 

int main( )

 {Student2 stud(10010,"Li",17,89);

  stud.show_all( );                            //输出学生的全部数据

return 0;

 }

#include <iostream>

#include <string>

using namespace std;

class Teacher                              //声明Teacher(教师)类

 {public:                                  //公用部分

   Teacher(string nam,int a,string t)      //构造函数

    {name=nam;

     age=a;

     title=t;}

   void display()                          //输出教师有关数据

     {cout<<"name:"<<name<<endl;

      cout<<"age"<<age<<endl;

      cout<<"title:"<<title<<endl;

     }

  protected:                               //保护部分

    string name;

    int age;

    string title;                          //职称

};

 

class Student                              //声明类Student(学生)

 {public:

   Student(string nam,char s,float sco)

     {name1=nam;

      sex=s;

      score=sco;}                         //构造函数

   void display1()                        //输出学生有关数据

    {cout<<"name:"<<name1<<endl;

     cout<<"sex:"<<sex<<endl;

     cout<<"score:"<<score<<endl;

    }

  protected:                               //保护部分

   string name1;

   char sex;

   float score;                            //成绩

 };

 

class Graduate:public Teacher,public Student   //声明多重继承的派生类Graduate

 {public:

   Graduate(string nam,int a,char s,string t,float sco,float w):

        Teacher(nam,a,t),Student(nam,s,sco),wage(w) {}

   void show( )                                 //输出人员的有关数据

    {cout<<"name:"<<name<<endl;

     cout<<"age:"<<age<<endl;

     cout<<"sex:"<<sex<<endl;

     cout<<"score:"<<score<<endl;

     cout<<"title:"<<title<<endl;

     cout<<"wages:"<<wage<<endl;

     }

  private:

    float wage;                     //工资

 };

 

int main( )

 {Graduate grad1("Wang-li",24,'f',"assistant",89.5,1234.5);

  grad1.show( );

  return 0;

}

#include <iostream>

#include <string>

using namespace std;

//定义公共基类Person

class Person                             

{public:

  Person(char *nam,char s,int a)            //构造函数    

   {strcpy(name,nam);sex=s;age=a;}

 protected:                                 //保护成员

   char name[20];

   char sex;

   int age;

};

//定义类Teacher

class Teacher:virtual public Person                //声明Person为公用继承的虚基类

 {public:                                

   Teacher(char *nam,char s,int a,char *t):Person(nam,s,a)       //构造函数

    {strcpy(title,t);

    }

  protected:                                       //保护成员

    char title[10];                                //职称

};

//定义类Student

class Student:virtual public Person               //声明Person为公用继承的虚基类

 {public:

   Student(char *nam,char s,int a,float sco):    //构造函数

      Person(nam,s,a),score(sco){}               //初始化表

  protected:                                     //保护成员

    float score;                                 //成绩

 };

//定义多重继承的派生类Graduate

class Graduate:public Teacher,public Student     //声明Teacher和Student类为公用继承的直接基类

 {public:

   Graduate(char *nam,char s,int a,char *t,float sco,float w):                  //构造函数

       Person(nam,s,a),Teacher(nam,s,a,t),Student(nam,s,a,sco),wage(w){}       //初始化表

    void show( )                                 //输出研究生的有关数据

    {cout<<"name:"<<name<<endl;

     cout<<"age:"<<age<<endl;

     cout<<"sex:"<<sex<<endl;

     cout<<"score:"<<score<<endl;

     cout<<"title:"<<title<<endl;

     cout<<"wages:"<<wage<<endl;

     }

  private:

    float wage;                     //工资

 };

 

int main( )

 {Graduate grad1("Wang-li",'f',24,"assistant",89.5,1234.5);

  grad1.show( );

  return 0;

}

#include <iostream>

#include <string>

using namespace std;

class Student

 {public:

   Student(int,string,float);

   void display();

  private:

   int num;

   string name;

   float score;

 };

 

Student::Student(int n,string nam,float s)

 {num=n;

  name=nam;

  score=s;

 }

 

void Student::display()

 {cout<<endl<<"num:"<<num<<endl;

  cout<<"name:"<<name<<endl;

  cout<<"score:"<<score<<endl;

 }

 

class Graduate:public Student

 {public:

   Graduate(int,string,float,float);

   void display();

 private:

  float pay;

};

 

void Graduate::display()

 {Student::display();

  cout<<"pay="<<pay<<endl;

 }

 

Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){}

 

int main()

 {Student stud1(1001,"Li",87.5);

  Graduate grad1(2001,"Wang",98.5,563.5);

  Student *pt=&stud1;

  pt->display();

  pt=&grad1;

  pt->display();

  return 0;

 }

 

#include <iostream.h>

//using namespace std;

//声明类Point

class Point

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

//定义Point类的成员函数

//Point的构造函数

Point::Point(float a,float b)

{x=a;y=b;}

//设置x和y的坐标值

void Point::setPoint(float a,float b)

{x=a;y=b;}

//输出点的坐标

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]"<<endl;

 return output;

}

int main()

{Point p(3.5,6.4);

 cout<<"x="<<p.getX()<<",y="<<p.getY()<<endl;

 p.setPoint(8.5,6.8);

 cout<<"p(new):"<<p<<endl;

 return 0;

}

#include <iostream>

using namespace std;

//声明类Point

class Point

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

//定义Point类的成员函数

//Point的构造函数

Point::Point(float a,float b)

{x=a;y=b;}

//设置x和y的坐标值

void Point::setPoint(float a,float b)

{x=a;y=b;}

//输出点的坐标

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]"<<endl;

 return output;

}

int main()

{Point p(3.5,6.4);

 cout<<"x="<<p.getX()<<",y="<<p.getY()<<endl;

 p.setPoint(8.5,6.8);

 cout<<"p(new):"<<p<<endl;

 return 0;

}

#include <iostream.h>

//using namespace std;

//声明类Point

class Point

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

//定义Point类的成员函数

//Point的构造函数

Point::Point(float a,float b)

{x=a;y=b;}

//设置x和y的坐标值

void Point::setPoint(float a,float b)

{x=a;y=b;}

//输出点的坐标

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]"<<endl;

 return output;

}

 

class Circle:public Point

{public:

  Circle(float x=0,float y=0,float r=0);

  void setRadius(float);

  float getRadius() const;

  float area () const;

  friend ostream &operator<<(ostream &,const Circle &);

 private:

  float radius;

};

 

Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}

 

void Circle::setRadius(float r)

{radius=r;}

 

float Circle::getRadius() const {return radius;}

 

float Circle::area() const

{return 3.14159*radius*radius;}

 

ostream &operator<<(ostream &output,const Circle &c)

{output<<"Center=["<<c.x<<","<<c.y<<"], Radius="<<c.radius<<", area="<<c.area()<<endl;

 return output;

}

 

int main()

{Circle c(3.5,6.4,5.2);

 cout<<"original circle:\nx="<<c.getX()<<", y="<<c.getY()<<", r="<<c.getRadius()

     <<", area="<<c.area()<<endl;

 c.setRadius(7.5);

 c.setPoint(5,5);

 cout<<"new circle:\n"<<c;

 Point &pRef=c;

 cout<<"pRef:"<<pRef;

 return 0;

}

#include <iostream>

using namespace std;

//声明类Point

class Point

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

//定义Point类的成员函数

//Point的构造函数

Point::Point(float a,float b)

{x=a;y=b;}

//设置x和y的坐标值

void Point::setPoint(float a,float b)

{x=a;y=b;}

//输出点的坐标

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]"<<endl;

 return output;

}

 

class Circle:public Point

{public:

  Circle(float x=0,float y=0,float r=0);

  void setRadius(float);

  float getRadius() const;

  float area () const;

  friend ostream &operator<<(ostream &,const Circle &);

 private:

  float radius;

};

 

Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}

 

void Circle::setRadius(float r)

{radius=r;}

 

float Circle::getRadius() const {return radius;}

 

float Circle::area() const

{return 3.14159*radius*radius;}

 

ostream &operator<<(ostream &output,const Circle &c)

{output<<"Center=["<<c.x<<","<<c.y<<"], Radius="<<c.radius<<", area="<<c.area()<<endl;

 return output;

}

 

int main()

{Circle c(3.5,6.4,5.2);

 cout<<"original circle:\nx="<<c.getX()<<", y="<<c.getY()<<", r="<<c.getRadius()

     <<", area="<<c.area()<<endl;

 c.setRadius(7.5);

 c.setPoint(5,5);

 cout<<"new circle:\n"<<c;

 Point &pRef=c;

 cout<<"pRef:"<<pRef;

 return 0;

}

#include <iostream.h>

class Point

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

 

Point::Point(float a,float b)

{x=a;y=b;}

void Point::setPoint(float a,float b)

{x=a;y=b;}

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]"<<endl;

 return output;

}

 

class Circle:public Point

{public:

  Circle(float x=0,float y=0,float r=0);

  void setRadius(float);

  float getRadius() const;

  float area () const;

  friend ostream &operator<<(ostream &,const Circle &);

 protected:

  float radius;

};

 

Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}

 

void Circle::setRadius(float r)

{radius=r;}

 

float Circle::getRadius() const {return radius;}

 

float Circle::area() const

{return 3.14159*radius*radius;}

 

ostream &operator<<(ostream &output,const Circle &c)

{output<<"Center=["<<c.x<<","<<c.y<<"], r="<<c.radius<<", area="<<c.area()<<endl;

 return output;

}

 

class Cylinder:public Circle

{public:

  Cylinder (float x=0,float y=0,float r=0,float h=0);

  void setHeight(float);

  float getHeight() const;

  float area() const;

  float volume() const;

  friend ostream& operator<<(ostream&,const Cylinder&);

 protected:

  float height;

};

 

Cylinder::Cylinder(float a,float b,float r,float h)

    :Circle(a,b,r),height(h){}

 

void Cylinder::setHeight(float h){height=h;}

 

float Cylinder::getHeight() const {return height;}

 

float Cylinder::area() const

{ return 2*Circle::area()+2*3.14159*radius*height;}

 

float Cylinder::volume() const

{return Circle::area()*height;}

 

ostream &operator<<(ostream &output,const Cylinder& cy)

{output<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height

       <<"\narea="<<cy.area()<<", volume="<<cy.volume()<<endl;

 return output;

}

 

int main()

{Cylinder cy1(3.5,6.4,5.2,10);

 cout<<"\noriginal cylinder:\nx="<<cy1.getX()<<", y="<<cy1.getY()<<", r="

     <<cy1.getRadius()<<", h="<<cy1.getHeight()<<"\narea="<<cy1.area()

     <<", volume="<<cy1.volume()<<endl;

 cy1.setHeight(15);

 cy1.setRadius(7.5);

 cy1.setPoint(5,5);

 cout<<"\nnew cylinder:\n"<<cy1;

 Point &pRef=cy1;

 cout<<"\npRef as a point:"<<pRef;

 Circle &cRef=cy1;

 cout<<"\ncRef as a Circle:"<<cRef;

 return 0;

}

#include <iostream>

using namespace std;

class Point

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

 

Point::Point(float a,float b)

{x=a;y=b;}

void Point::setPoint(float a,float b)

{x=a;y=b;}

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]"<<endl;

 return output;

}

 

class Circle:public Point

{public:

  Circle(float x=0,float y=0,float r=0);

  void setRadius(float);

  float getRadius() const;

  float area () const;

  friend ostream &operator<<(ostream &,const Circle &);

 protected:

  float radius;

};

 

Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}

 

void Circle::setRadius(float r)

{radius=r;}

 

float Circle::getRadius() const {return radius;}

 

float Circle::area() const

{return 3.14159*radius*radius;}

 

ostream &operator<<(ostream &output,const Circle &c)

{output<<"Center=["<<c.x<<","<<c.y<<"], r="<<c.radius<<", area="<<c.area()<<endl;

 return output;

}

 

class Cylinder:public Circle

{public:

  Cylinder (float x=0,float y=0,float r=0,float h=0);

  void setHeight(float);

  float getHeight() const;

  float area() const;

  float volume() const;

  friend ostream& operator<<(ostream&,const Cylinder&);

 protected:

  float height;

};

 

Cylinder::Cylinder(float a,float b,float r,float h)

    :Circle(a,b,r),height(h){}

 

void Cylinder::setHeight(float h){height=h;}

 

float Cylinder::getHeight() const {return height;}

 

float Cylinder::area() const

{ return 2*Circle::area()+2*3.14159*radius*height;}

 

float Cylinder::volume() const

{return Circle::area()*height;}

 

ostream &operator<<(ostream &output,const Cylinder& cy)

{output<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height

       <<"\narea="<<cy.area()<<", volume="<<cy.volume()<<endl;

 return output;

}

 

int main()

{Cylinder cy1(3.5,6.4,5.2,10);

 cout<<"\noriginal cylinder:\nx="<<cy1.getX()<<", y="<<cy1.getY()<<", r="

     <<cy1.getRadius()<<", h="<<cy1.getHeight()<<"\narea="<<cy1.area()

     <<", volume="<<cy1.volume()<<endl;

 cy1.setHeight(15);

 cy1.setRadius(7.5);

 cy1.setPoint(5,5);

 cout<<"\nnew cylinder:\n"<<cy1;

 Point &pRef=cy1;

 cout<<"\npRef as a point:"<<pRef;

 Circle &cRef=cy1;

 cout<<"\ncRef as a Circle:"<<cRef;

 return 0;

}

#include <iostream>

#include <string>

using namespace std;

class Student

 {public:

   Student(int,string,float);

   void display();

  protected:

   int num;

   string name;

   float score;

 };

 

Student::Student(int n,string nam,float s)

 {num=n;name=nam;score=s;}

 

void Student::display()

 {cout<<"num:"<<num<<"\nname:"<<name<<"\nscore:"<<score<<"\n\n";}

 

class Graduate:public Student

 {public:

   Graduate(int,string,float,float);

   void display();

  private:

   float pay;

};

 

void Graduate::display()

 {cout<<"num:"<<num<<"\nname:"<<name<<"\nscore:"<<score<<"\npay="<<pay<<endl;}

 

Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){}

 

int main()

 {Student stud1(1001,"Li",87.5);

  Graduate grad1(2001,"Wang",98.5,563.5);

  Student *pt=&stud1;

  pt->display();

  pt=&grad1;

  pt->display();

  return 0;

 }

  #include <iostream>

#include <string>

using namespace std;

class Student

 {public:

   Student(int,string,float);

   virtual void display();

  protected:

   int num;

   string name;

   float score;

 };

 

Student::Student(int n,string nam,float s)

 {num=n;name=nam;score=s;}

 

void Student::display()

 {cout<<"num:"<<num<<"\nname:"<<name<<"\nscore:"<<score<<"\n\n";}

 

class Graduate:public Student

 {public:

   Graduate(int,string,float,float);

   void display();

 private:

  float pay;

};

 

void Graduate::display()

 {cout<<"num:"<<num<<"\nname:"<<name<<"\nscore:"<<score<<"\npay="<<pay<<endl;}

 

Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){}

 

int main()

 {Student stud1(1001,"Li",87.5);

  Graduate grad1(2001,"Wang",98.5,1200);

  Student *pt=&stud1;

  pt->display();

  pt=&grad1;

  pt->display();

  return 0;

 }

#include <iostream>

using namespace std;

class Point

{public:

  Point(){}

  ~Point(){cout<<"executing Point destructor"<<endl;}

};

 

class Circle:public Point

{public:

  Circle(){}

  ~Circle(){cout<<"executing Circle destructor"<<endl;}

 private:

  int radus;

};

 

int main()

{Point *p=new Circle;

 delete p;

 return 0;

}

#include <iostream>

using namespace std;

class Point

{public:

  Point(){}

  virtual ~Point(){cout<<"executing Point destructor"<<endl;}

};

 

class Circle:public Point

{public:

  Circle(){}

  ~Circle(){cout<<"executing Circle destructor"<<endl;}

 private:

  int radus;

};

 

void main()

{Point *p=new Circle;

 delete p;

}

#include <iostream.h>

//声明抽象基类Shape

class Shape

{public:

 virtual float area() const {return 0.0;}        //虚函数

 virtual float volume() const {return 0.0;}      //虚函数

 virtual void shapeName() const =0;              //纯虚函数

};

 

//声明Point类

class Point:public Shape                         //Point是Shape的公用派生类

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  virtual void shapeName() const {cout<<"Point:";}  //对纯虚函数进行定义

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

 

Point::Point(float a,float b)

{x=a;y=b;}

 

void Point::setPoint(float a,float b)

{x=a;y=b;}

 

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]";

 return output;

}

 

//声明Circle类

class Circle:public Point

{public:

  Circle(float x=0,float y=0,float r=0);

  void setRadius(float);

  float getRadius() const;

  virtual float area() const;

  virtual void shapeName() const {cout<<"Circle:";}         //对纯虚函数进行再定义

  friend ostream &operator<<(ostream &,const Circle &);

 protected:

  float radius;

};

 

Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}

 

void Circle::setRadius(float r)

{radius=r;}

 

float Circle::getRadius() const {return radius;}

 

float Circle::area() const

{return 3.14159*radius*radius;}

 

ostream &operator<<(ostream &output,const Circle &c)

{output<<"["<<c.x<<","<<c.y<<"], r="<<c.radius;

 return output;

}

 

//声明Cylinder类

class Cylinder:public Circle

{public:

  Cylinder (float x=0,float y=0,float r=0,float h=0);

  void setHeight(float);

  float getHeight() const;

  virtual float area() const;

  virtual float volume() const;

  virtual void shapeName() const {cout<<"Cylinder:";}         //对纯虚函数进行再定义

  friend ostream& operator<<(ostream&,const Cylinder&);

 protected:

  float height;

};

 

Cylinder::Cylinder(float a,float b,float r,float h)

    :Circle(a,b,r),height(h){}

 

void Cylinder::setHeight(float h){height=h;}

 

float Cylinder::getHeight() const {return height;}

 

float Cylinder::area() const

{ return 2*Circle::area()+2*3.14159*radius*height;}

 

float Cylinder::volume() const

{return Circle::area()*height;}

 

ostream &operator<<(ostream &output,const Cylinder& cy)

{output<<"["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height;

 return output;

}

 

int main()

{Point point(3.2,4.5);                           //建立Point类对象point

 Circle circle(2.4,12,5.6);                      //建立Circle类对象circle

 Cylinder cylinder(3.5,6.4,5.2,10.5);            //建立Cylinder类对象cylinder

 

 point.shapeName();                              //静态关联

 cout<<point<<endl;

 

 circle.shapeName();                             //静态关联

 cout<<circle<<endl;

 

 cylinder.shapeName();                           //静态关联

 cout<<cylinder<<endl<<endl;

 

 Shape *pt;                                      //定义基类指针

 

 pt=&point;                                      //指针指向Point类对象

 pt->shapeName();                                //动态关联

 cout<<"x="<<point.getX()<<",y="<<point.getY()<<"\narea="<<pt->area()

     <<"\nvolume="<<pt->volume()<<"\n\n";

 

 pt=&circle;                                     //指针指向Circle类对象

 pt->shapeName();                                //动态关联

 cout<<"x="<<circle.getX()<<",y="<<circle.getY()<<"\narea="<<pt->area()

     <<"\nvolume="<<pt->volume()<<"\n\n";

 

 pt=&cylinder;                                   //指针指向Cylinder类对象

 pt->shapeName();                                //动态关联

 cout<<"x="<<cylinder.getX()<<",y="<<cylinder.getY()<<"\narea="<<pt->area()

     <<"\nvolume="<<pt->volume()<<"\n\n";

 return 0;

}

#include <iostream>

using namespace std;

//声明抽象基类Shape

class Shape

{public:

 virtual float area() const {return 0.0;}        //虚函数

 virtual float volume() const {return 0.0;}      //虚函数

 virtual void shapeName() const =0;              //纯虚函数

};

 

//声明Point类

class Point:public Shape                         //Point是Shape的公用派生类

{public:

  Point(float=0,float=0);

  void setPoint(float,float);

  float getX() const {return x;}

  float getY() const {return y;}

  virtual void shapeName() const {cout<<"Point:";}  //对纯虚函数进行定义

  friend ostream & operator<<(ostream &,const Point &);

protected:

  float x,y;

};

 

Point::Point(float a,float b)

{x=a;y=b;}

 

void Point::setPoint(float a,float b)

{x=a;y=b;}

 

ostream & operator<<(ostream &output,const Point &p)

{output<<"["<<p.x<<","<<p.y<<"]";

 return output;

}

 

//声明Circle类

class Circle:public Point

{public:

  Circle(float x=0,float y=0,float r=0);

  void setRadius(float);

  float getRadius() const;

  virtual float area() const;

  virtual void shapeName() const {cout<<"Circle:";}         //对纯虚函数进行再定义

  friend ostream &operator<<(ostream &,const Circle &);

 protected:

  float radius;

};

 

Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}

 

void Circle::setRadius(float r)

{radius=r;}

 

float Circle::getRadius() const {return radius;}

 

float Circle::area() const

{return 3.14159*radius*radius;}

 

ostream &operator<<(ostream &output,const Circle &c)

{output<<"["<<c.x<<","<<c.y<<"], r="<<c.radius;

 return output;

}

 

//声明Cylinder类

class Cylinder:public Circle

{public:

  Cylinder (float x=0,float y=0,float r=0,float h=0);

  void setHeight(float);

  float getHeight() const;

  virtual float area() const;

  virtual float volume() const;

  virtual void shapeName() const {cout<<"Cylinder:";}         //对纯虚函数进行再定义

  friend ostream& operator<<(ostream&,const Cylinder&);

 protected:

  float height;

};

 

Cylinder::Cylinder(float a,float b,float r,float h)

    :Circle(a,b,r),height(h){}

 

void Cylinder::setHeight(float h){height=h;}

 

float Cylinder::getHeight() const {return height;}

 

float Cylinder::area() const

{ return 2*Circle::area()+2*3.14159*radius*height;}

 

float Cylinder::volume() const

{return Circle::area()*height;}

 

ostream &operator<<(ostream &output,const Cylinder& cy)

{output<<"["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height;

 return output;

}

 

int main()

{Point point(3.2,4.5);                           //建立Point类对象point

 Circle circle(2.4,12,5.6);                      //建立Circle类对象circle

 Cylinder cylinder(3.5,6.4,5.2,10.5);            //建立Cylinder类对象cylinder

 

 point.shapeName();                              //静态关联

 cout<<point<<endl;

 

 circle.shapeName();                             //静态关联

 cout<<circle<<endl;

 

 cylinder.shapeName();                           //静态关联

 cout<<cylinder<<endl<<endl;

 

 Shape *pt;                                      //定义基类指针

 

 pt=&point;                                      //指针指向Point类对象

 pt->shapeName();                                //动态关联

 cout<<"x="<<point.getX()<<",y="<<point.getY()<<"\narea="<<pt->area()

     <<"\nvolume="<<pt->volume()<<"\n\n";

 

 pt=&circle;                                     //指针指向Circle类对象

 pt->shapeName();                                //动态关联

 cout<<"x="<<circle.getX()<<",y="<<circle.getY()<<"\narea="<<pt->area()

     <<"\nvolume="<<pt->volume()<<"\n\n";

 

 pt=&cylinder;                                   //指针指向Cylinder类对象

 pt->shapeName();                                //动态关联

 cout<<"x="<<cylinder.getX()<<",y="<<cylinder.getY()<<"\narea="<<pt->area()

     <<"\nvolume="<<pt->volume()<<"\n\n";

 return 0;

}

#include <iostream>

#include <math.h>

using namespace std;

int main()

{float a,b,c,disc;

 cout<<"please input a,b,c:";

 cin>>a>>b>>c;

 if (a==0)

  cerr<<"a is equal to zero,error!"<<endl;

 else

  if ((disc=b*b-4*a*c)<0)

   cerr<<"disc=b*b-4*a*c<0"<<endl;

  else

   {cout<<"x1="<<(-b+sqrt(disc))/(2*a)<<endl;

    cout<<"x2="<<(-b-sqrt(disc))/(2*a)<<endl;

   }

 return 0;

}

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{int a;

 cout<<"input a:";

 cin>>a;

 cout<<"dec:"<<dec<<a<<endl;

 cout<<"hex:"<<hex<<a<<endl;

 cout<<"oct:"<<setbase(8)<<a<<endl;

 char *pt="China";

 cout<<setw(10)<<pt<<endl;

 cout<<setfill('*')<<setw(10)<<pt<<endl;

 double pi=22.0/7.0;

 cout<<setiosflags(ios::scientific)<<setprecision(8);

 cout<<"pi="<<pi<<endl;

 cout<<"pi="<<setprecision(4)<<pi<<endl;

 cout<<"pi="<<setiosflags(ios::fixed)<<pi<<endl;

 return 0;

}

#include <iostream>

using namespace std;

int main()

{int a=21;

 cout.setf(ios::showbase);

 cout<<"dec:"<<a<<endl;

 cout.unsetf(ios::dec);

 cout.setf(ios::hex);

 cout<<"hex:"<<a<<endl;

 cout.unsetf(ios::hex);

 cout.setf(ios::oct);

 cout<<"oct:"<<a<<endl;

 char *pt="China";

 cout.width(10);

 cout<<pt<<endl;

 cout.width(10);

 cout.fill('*');

 cout<<pt<<endl;

 double pi=22.0/7.0;

 cout.setf(ios::scientific);

 cout<<"pi=";

 cout.width(14);

 cout<<pi<<endl;

 cout.unsetf(ios::scientific);

 cout.setf(ios::fixed);

 cout.width(12);

 cout.setf(ios::showpos);

 cout.setf(ios::internal);

 cout.precision(6);

 cout<<pi<<endl;

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char *a="BASIC";

 for(int i=4;i>=0;i--)

  cout.put(*(a+i));

 cout.put('\n');

 return 0;

}

#include <iostream>

int main()

{char *a="BASIC";

 for(int i=4;i>=0;i--)

  putchar(*(a+i));

 putchar('\n');

 return 0;

}

#include <iostream>

using namespace std;

int main()

{float grade;

 cout<<"enter grade:";

 while(cin>>grade)

  {if(grade>=85) cout<<grade<<" GOOD!"<<endl;

   if(grade<60) cout<<grade<<" fail!"<<endl;

   cout<<"enter grade:";

  }

 cout<<"The end."<<endl;

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char c;

 cout<<"enter a sentence:"<<endl;

 while((c=cin.get())!=EOF)

  cout.put(c);

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char c;

 cout<<"enter a sentence:"<<endl;

 while(cin.get(c))

  {cout.put(c);

  }

 cout<<"end"<<endl;

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char ch[20];

 cout<<"enter a sentence:"<<endl;

 cin.get(ch,10,'\n');

 cout<<ch<<endl;

 return 0;

}

 

#include <iostream>

using namespace std;

int main()

{char ch[20];

 cout<<"enter a sentence:"<<endl;

 cin>>ch;

 cout<<"The string read with cin is:"<<ch<<endl;

 cin.getline(ch,20,'/');

 cout<<"The second part is:"<<ch<<endl;

 cin.getline(ch,20);

 cout<<"The third part is:"<<ch<<endl;

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char c;

 while(!cin.eof())

  if((c=cin.get())!=' ')

     cout.put(c);

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char c[20];

 int ch;

 cout<<"please enter a sentence."<<endl;

 cin.getline(c,15,'/');

 cout<<"The first part is:"<<c<<endl;

 ch=cin.peek();

 cout<<"The next character(ASCII code) is:"<<ch<<endl;

 cin.putback(c[0]);

 cin.getline(c,15,'/');

 cout<<"The second part is:"<<c<<endl;

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char ch[20];

 cin.get(ch,20,'/');

 cout<<"The first part is:"<<ch<<endl;

 cin.get(ch,20,'/');

 cout<<"The second part is:"<<ch<<endl;

 return 0;

}

#include <iostream>

using namespace std;

int main()

{char ch[20];

 cin.get(ch,20,'/');

 cout<<"The first part is:"<<ch<<endl;

 cin.ignore();

 cin.get(ch,20,'/');

 cout<<"The second part is:"<<ch<<endl;

 return 0;

}

#include <fstream>

using namespace std;

int main()

{int a[10];

 ofstream outfile("f1.dat");

 if(!outfile)

  {cerr<<"open error!"<<endl;

   exit(1);

  }

 cout<<"enter 10 integer numbers:"<<endl;

 for(int i=0;i<10;i++)

  {cin>>a[i];

   outfile<<a[i]<<" ";}

 outfile.close();

 return 0;

}

#include <fstream>

using namespace std;

int main()

{int a[10],max,i,order;

 ifstream infile("f1.dat",ios::in);

 if(!infile)

  {cerr<<"open error!"<<endl;

   exit(1);

  }

 for(i=0;i<10;i++)

   {infile>>a[i];

    cout<<a[i]<<" ";}

 cout<<endl;

 max=a[0];

 order=0;

 for(i=1;i<10;i++)

   if(a[i]>max)

     {max=a[i];

      order=i;

     }

 cout<<"max="<<max<<endl<<"order="<<order<<endl;

 infile.close();

 return 0;

}

#include <fstream>

using namespace std;

void save_to_file()

{ofstream outfile("f2.dat");

 if(!outfile)

  {cerr<<"open f2.dat error!"<<endl;

   exit(1);

  }

 char c[80];

 cin.getline(c,80);

 for(int i=0;c[i];i++)

  if(c[i]>=65 && c[i]<=90||c[i]>=97 && c[i]<=122)

    {outfile.put(c[i]);

     cout<<c[i];}

 cout<<endl;

 outfile.close();

}

 

void get_from_file()

{char ch;

 ifstream infile("f2.dat",ios::in);

 if(!infile)

  {cerr<<"open f2.dat error!"<<endl;

   exit(1);

  }

 ofstream outfile("f3.dat");

 if(!outfile)

  {cerr<<"open f3.dat error!"<<endl;

   exit(1);

  }

 while(infile.get(ch))

  {if(ch>=97 && ch<=122)

     ch=ch-32;

   outfile.put(ch);

   cout<<ch;

  }

 cout<<endl;

 infile.close();

 outfile.close();

}

int main()

{save_to_file();

 get_from_file();

 return 0;

}

#include <fstream>

using namespace std;

void display_file(char *filename)

{ifstream infile(filename,ios::in);

 if(!infile)

  {cerr<<"open error!"<<endl;

   exit(1);}

 char ch;

 while(infile.get(ch))

   cout.put(ch);

 cout<<endl;

 infile.close();

}

int main()

{display_file("f3.dat");

 return 0;

}

#include <fstream>

using namespace std;

struct student

{char name[20];

 int num;

 int age;

 char sex;

};

int main()

{student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};

 ofstream outfile("stud.dat",ios::binary);

 if(!outfile)

  {cerr<<"open error!"<<endl;

   abort();

  }

 for(int i=0;i<3;i++)

   outfile.write((char *)&stud[i],sizeof(stud[i]));

  outfile.close();

 return 0;

}

#include <fstream>

using namespace std;

struct student

{char name[20];

 int num;

 int age;

 char sex;

};

int main()

{student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};

 ofstream outfile("stud.dat",ios::binary);

 if(!outfile)

  {cerr<<"open error!"<<endl;

   abort();

  }

  outfile.write((char *)&stud[0],sizeof(stud));

  outfile.close();

  return 0;

}

#include <fstream>

using namespace std;

struct student

{char name[20];

 int num;

 int age;

 char sex;

 };

int main()

{student stud[3];

 int i;

 ifstream infile("stud.dat",ios::binary);

 if(!infile)

  {cerr<<"open error!"<<endl;

   abort();

  }

  for(i=0;i<3;i++)

   infile.read((char*)&stud[i],sizeof(stud[i]));

  infile.close();

  for(i=0;i<3;i++)

   {cout<<"NO."<<i+1<<endl;

    cout<<"name:"<<stud[i].name<<endl;

    cout<<"num:"<<stud[i].num<<endl;;

    cout<<"age:"<<stud[i].age<<endl;

    cout<<"sex:"<<stud[i].sex<<endl<<endl;

   }

   return 0;

  }

#include <fstream>

using namespace std;

struct student

{int num;

 char name[20];

 float score;

};

int main()

{int i;

 student stud[5]={1001,"Li",85,1002,"Fun",97.5,1004,"Wang",54,

                  1006,"Tan",76.5,1010,"ling",96};

 fstream iofile("stud.dat",ios::in|ios::out|ios::binary);

 if(!iofile)

  {cerr<<"open error!"<<endl;

   abort();

  }

 for(i=0;i<5;i++)

   iofile.write((char *)&stud[i],sizeof(stud[i]));

 student stud1[5];

 for(i=0;i<5;i=i+2)

   {iofile.seekg(i*sizeof(stud[i]),ios::beg);

    iofile.read((char *)&stud1[i/2],sizeof(stud1[i]));

    cout<<stud1[i/2].num<<" "<<stud1[i/2].name<<" "<<stud1[i/2].score<<endl;

   }

 cout<<endl;

 stud[2].num=1012;

 strcpy(stud[2].name,"Wu");

 stud[2].score=60;

 iofile.seekp(2*sizeof(stud[0]),ios::beg);

 iofile.write((char *)&stud[2],sizeof(stud[2]));

 iofile.seekg(0,ios::beg);

 for(i=0;i<5;i++)

   {iofile.read((char *)&stud[i],sizeof(stud[i]));

    cout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<endl;

   }

 iofile.close();

 return 0;

}

#include <strstream>

#include <iostream>

using namespace std;

struct student

{int num;

 char name[20];

 float score;

};

int main()

{student stud[3]={1001,"Li",78,1002,"Wang",89.5,1004,"Fun",90};

 char c[50];

 ostrstream strout(c,30);

 for(int i=0;i<3;i++)

  strout<<stud[i].num<<stud[i].name<<stud[i].score;

 strout<<ends;

 cout<<"array c:"<<endl<<c<<endl;

 return 0;

}

#include <strstream>

#include <iostream>

using namespace std;

int main()

{char c[50]="12 34 65 -23 -32 33 61 99 321 32";

 int a[10],i,j,t;

 cout<<"array c:"<<c<<endl;

 istrstream strin(c,sizeof(c));

 for(i=0;i<10;i++)

  strin>>a[i];

 cout<<"array a:";

 for(i=0;i<10;i++)

   cout<<a[i]<<" ";

 cout<<endl;

 for(i=0;i<9;i++)

   for(j=0;j<9-i;j++)

      if(a[j]>a[j+1])

        {t=a[j];a[j]=a[j+1];a[j+1]=t;}

 ostrstream strout(c,sizeof(c));

 for(i=0;i<10;i++)

   strout<<a[i]<<" ";

 strout<<ends;

 cout<<"array c:"<<c<<endl;

 return 0;

}

#include <iostream>

#include <cmath>

using namespace std;

int main()

{double triangle(double,double,double);

 double a,b,c;

 cin>>a>>b>>c;

   while(a>0 && b>0 && c>0)

    {cout<<triangle(a,b,c)<<endl;

     cin>>a>>b>>c;

    }

 return 0;

}

 

double triangle(double a,double b,double c)

{double area;

 double s=(a+b+c)/2;

 area=sqrt(s*(s-a)*(s-b)*(s-c));

 return area;

}

#include <iostream>

#include <cmath>

using namespace std;

int main()

{double triangle(double,double,double);

 double a,b,c;

 cin>>a>>b>>c;

 try

  {while(a>0 && b>0 && c>0)

    {cout<<triangle(a,b,c)<<endl;

     cin>>a>>b>>c;}

  }

 catch(double)

  {cout<<"a="<<a<<",b="<<b<<",c="<<c<<",that is not a traingle!"<<endl;}

 cout<<"end"<<endl;

 return 0;

}

 

double triangle(double a,double b,double c)

{double s=(a+b+c)/2;

 if (a+b<=c||b+c<=a||c+a<=b) throw a;

 return sqrt(s*(s-a)*(s-b)*(s-c));

}

#include <iostream>

using namespace std;

int main()

{void f1();

 try

  {f1();}

 catch(double)

  {cout<<"OK0!"<<endl;}

 cout<<"end0"<<endl;

 return 0;

}

void f1()

{void f2();

 try

  {f2();}

 catch(char)

  {cout<<"OK1!";}

 cout<<"end1"<<endl;

}

 

void f2()

{void f3();

 try

 {f3();}

 catch(int)

 {cout<<"Ok2!"<<endl;}

 cout<<"end2"<<endl;

}

void f3()

{double a=0;

 try

  {throw a;}

 catch(float)

  {cout<<"OK3!"<<endl;}

 cout<<"end3"<<endl;

}

#include <iostream>

using namespace std;

int main()

{void f1();

 try

  {f1();}

 catch(double)

  {cout<<"OK0!"<<endl;}

 cout<<"end0"<<endl;

 return 0;

}

 

void f1()

{void f2();

 try

  {f2();}

 catch(char)

  {cout<<"OK1!";}

 cout<<"end1"<<endl;

}

 

void f2()

{void f3();

 try

 {f3();}

 catch(int)

 {cout<<"Ok2!"<<endl;}

 cout<<"end2"<<endl;

}

void f3()

{double a=0;

 try

  {throw a;}

 catch(double)

  {cout<<"OK3!"<<endl;}

 cout<<"end3"<<endl;

}

#include <iostream>

using namespace std;

int main()

{void f1();

 try

  {f1();}

 catch(double)

  {cout<<"OK0!"<<endl;}

 cout<<"end0"<<endl;

 return 0;

}

 

void f1()

{void f2();

 try

  {f2();}

 catch(char)

  {cout<<"OK1!";}

 cout<<"end1"<<endl;

}

 

void f2()

{void f3();

 try

 {f3();}

 catch(int)

 {cout<<"Ok2!"<<endl;}

 cout<<"end2"<<endl;

}

void f3()

{double a=0;

 try

  {throw a;}

 catch(double)

  {cout<<"OK3!"<<endl;throw;}

 cout<<"end3"<<endl;

}

#include <iostream>

#include <string>

using namespace std;

class Student

 {public:

   Student(int n,string nam)

    {cout<<"construtot-"<<n<<endl;

     num=n;name=nam;}

   ~Student(){cout<<"destructor-"<<num<<endl;}

   void get_data();

  private:

   int num;

   string name;

 };

void Student::get_data()

 {if(num==0) throw num;

  else cout<<num<<" "<<name<<endl;

  cout<<"in get_data()"<<endl;

 }

 

void fun()

{Student stud1(1101,"tan");

 stud1.get_data();

 Student stud2(0,"Li");

 stud2.get_data();

}

int main()

{cout<<"main begin"<<endl;

 cout<<"call fun()"<<endl;

 try

  {fun();}

 catch(int n)

  {cout<<"num="<<n<<",error!"<<endl;}

 cout<<"main end"<<endl;

 return 0;

}

 #include <iostream>

using namespace std;

#include "header1.h"

int main()

 {Student stud1(101,"Wang",18);

  stud1.get_data();

  cout<<fun(5,3)<<endl;

  return 0;

 }

  #include <iostream>

using namespace std;

#include "header1.h"

#include "header2.h"

int main()

 {Student stud1(101,"Wang",18);

  stud1.get_data();

  cout<<fun(5,3)<<endl;

  return 0;

 }

  //main file

#include <iostream>

#include "header11.h"

#include "header22.h"

int main()

 {Ns1::Student stud1(101,"Wang",18);

  stud1.get_data();

  cout<<Ns1::fun(5,3)<<endl;

  Ns2::Student stud2(102,"Li",'f');

  stud2.get_data();

  cout<<Ns2::fun(5,3)<<endl;

  return 0;

 }

//例14.4中的头文件header1

#include <string>

#include <cmath>

using namespace std;

class Student

 {public:

   Student(int n,string nam,int a)

     {num=n;name=nam;age=a;}

   void get_data();

  private:

   int num;

   string name;

   int age;

 };

void Student::get_data()

 {cout<<num<<" "<<name<<" "<<age<<endl;

 }

double fun(double a,double b)

 {return sqrt(a+b);}

//例14.4中的头文件header2

#include <string>

#include <cmath>

using namespace std;

class Student

 {public:

   Student(int n,string nam,char s)

     {num=n;name=nam;sex=s;}

   void get_data();

  private:

   int num;

   string name;

   char sex;

 };

void Student::get_data()

 {cout<<num<<" "<<name<<" "<<sex<<endl;

 }

double fun(double a,double b)

 {return sqrt(a-b);}

//例14.5中的头文件1,文件名为header11.h

using namespace std;

#include <string>

#include <cmath>

namespace Ns1

 {class Student

    {public:

      Student(int n,string nam,int a)

       {num=n;name=nam;age=a;}

      void get_data();

     private:

      int num;

      string name;

      int age;

    };

 void Student::get_data()

    {cout<<num<<" "<<name<<" "<<age<<endl;

    }

   

 double fun(double a,double b)

    {return sqrt(a+b);}

 }

//例14.5中的头文件2,文件名为header12.h

#include <string>

#include <cmath>

namespace Ns2

 {class Student

   {public:

     Student(int n,string nam,char s)

       {num=n;name=nam;sex=s;}

     void get_data();

    private:

     int num;

     string name;

     char sex;

   };

  

  void Student::get_data()

   {cout<<num<<" "<<name<<" "<<sex<<endl;

   }

  double fun(double a,double b)

   {return sqrt(a-b);}

 }

转载于:https://www.cnblogs.com/Aha-Best/p/10912991.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值