码迷,mamicode.com
首页 > 其他好文 > 详细

类模板

时间:2017-03-18 23:20:34      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:iostream   括号   不同的   cout   stream   为什么   space   pre   表达   

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

#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...\n";
    return 0;
}

 说明,

Child2(T a) :Parent<T>(1.29)
也可以写成
Child2(T a) :Parent(1.29)
上面不是说类模板不能隐式推断类型,必须显式在<>中表明类型吗?
那为什么这里又可以不用了呢?
因为我们之前在继承的时候已经声明了
class Child2 :public Parent<T>
在这个类中,可以不再使用<T>显式表达类型,但是,在这个声明语句
class Child2 :public Parent<T> 中的Parent<T>中的显式表达类型<T>是必须要的,后面在构造函数初始化列表父类时,可以不用再指明类型,但是,建议还是都显式类型表示

类模板

标签:iostream   括号   不同的   cout   stream   为什么   space   pre   表达   

原文地址:http://www.cnblogs.com/yangguang-it/p/6576343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!