孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

设有程序

$ cat -n base2.cpp
     1    #include <iostream>
     2    using namespace std;
     3    class Base
     4    {
     5        int x;
     6        public:
     7            Base(int i) {x=i;}
     8            int getx() {return x;}
     9            void disp() {cout<<"The value of x in Base is: "<<x<<endl;}
    10    };
    11    template <class T>
    12    class Derived:public Base
    13    {
    14        T y;
    15        public:
    16            Derived(T a,int j):Base(j){y=a;}
    17            T gety(){return y;}   
    18            void disp()
    19            {cout<<"The value of y in Derived is : "<<y<<", and x in Derived is: "<<gety()<<endl;}
    20    };
    21    int main()
    22    {
    23        Base obj_B(888);
    24        obj_B.disp();
    25        Derived<int> obj_D1(1,2);
    26        Derived<double> obj_D2(8.8,6);
    27        Derived<char *> obj_D3("zrf",10);
    28        Derived<char> obj_D4('=',20);
    29        obj_D1.disp();
    30        obj_D2.disp();
    31        obj_D3.disp();
    32        obj_D4.disp();
    33   
    34    }

则其运行结果为:

$ ./base2
The value of x in Base is: 888
The value of y in Derived is : 1, and x in Derived is: 1
The value of y in Derived is : 8.8, and x in Derived is: 8.8
The value of y in Derived is : zrf, and x in Derived is: zrf
The value of y in Derived is : =, and x in Derived is: =

然后将template <class T>改为template <typename T>,重新编译,运行结果一样,这样就证明了class T等价于typename T

posted on 2011-05-22 20:59  孤独的猫  阅读(436)  评论(0编辑  收藏  举报