C++的模板类应用举例

简介: 设有程序 $ cat -n base2.cpp     1    #include      2    using namespace std;     3    class Base     4    {     5        int x;     6        public:     ...

设有程序

$ 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

相关文章
|
2天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
17 0
|
2天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
1天前
|
设计模式 Java C++
【C++高阶(八)】单例模式&特殊类的设计
【C++高阶(八)】单例模式&特殊类的设计
|
1天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
5天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
7天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”
|
27天前
|
存储 C++ 容器
C++入门指南:string类文档详细解析(非常经典,建议收藏)
C++入门指南:string类文档详细解析(非常经典,建议收藏)
34 0
|
27天前
|
存储 编译器 C语言
C++入门: 类和对象笔记总结(上)
C++入门: 类和对象笔记总结(上)
32 0
|
7天前
|
编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”

热门文章

最新文章