zoukankan      html  css  js  c++  java
  • 类模板

    与函数模板不同的是,编译器不能为类模板推断模板参数的类型,为了使用类模板,我们必须在模板名后的尖括号中提供额外的消息---用来代替模板参数的模板实参列表。这些额外的信息是显式的模板实参列表,它们被绑定到模板参数。

    #include<iostream>
    using namespace std;
    
    template <typename T>
    class Parent {
    public:
        Parent(T a)
        {
            this->a = a;
        }
        virtual void printf()
        {
            cout << "a: " << a << endl;
        }
    private:
        T a;
    };
    
    class Child :public Parent<int>
    {
    public:
        Child(int a) :Parent<int>(100)
        {
            this->a = a;
        }
        void printf()override
        {
            cout << "a: " << a << endl;
        }
    private:
        int a;
    
    };
    template<typename T>
    class Child2 :public Parent<T> {
    public:
        Child2(T a) :Parent<T>(1.29)
        {
            this->a = a;
        }
        void printf()override
        {
            cout << "a: " << a << endl;
        }
    private:
        T a;
    };
    int main()
    {
        Parent<int> p1(10);
        Child c1(1);
        p1.printf();
        c1.printf();
        c1.Parent::printf();
    
        Child2<double> c2(11.2);
        c2.printf();
        c2.Parent::printf();
    
        cout << "hello...
    ";
        return 0;
    }

     说明,

    Child2(T a) :Parent<T>(1.29)
    也可以写成
    Child2(T a) :Parent(1.29)
    同理上面函数的如下语句:
    Child(int a) :Parent<int>(100)
    上面的<int>也可以省略。
    上面不是说类模板不能隐式推断类型,必须显式在<>中表明类型吗?
    那为什么这里又可以不用了呢?
    因为我们之前在继承的时候已经声明了
    class Child2 :public Parent<T>
    在这个类中,可以不再使用<T>显式表达类型,但是,在这个声明语句
    class Child2 :public Parent<T> 中的Parent<T>中的显式表达类型<T>是必须要的,后面在构造函数初始化列表父类时,可以不用再指明类型,但是,建议还是都显式类型表示。
    
    
  • 相关阅读:
    位运算的应用
    MySql的自增主键以及TEXT数据类型使用
    MaxDos启动盘拆解
    QT预备式(包含MySql配置)未完成……
    关于Services.exe开机CPU内存使用暴增解决方案
    Windows Upnp 服务补丁——UpnpFix V1.0
    Memory Ordering
    "FoxitReaderOCX.ocx failed to load" 问题解决方案
    LameDropXPd V2.0 (L.A.M.E 3.97) 完美汉化版
    编译QT的MySql驱动问题及解决方案
  • 原文地址:https://www.cnblogs.com/yangguang-it/p/6576343.html
Copyright © 2011-2022 走看看