【问题标题】:Inheritance of templated class members in constructor构造函数中模板化类成员的继承
【发布时间】:2013-05-07 15:29:37
【问题描述】:

我发布了一个非常相似的question 并得到了我的答案。我现在面临与构造函数相同的问题.. 如何为 T2 编写构造函数?

template<typename T>
class T1
{
    public:
      T1(int t) : m_t(t) {}

    protected:
    int m_t;
};

template<typename T>
class T2 : public T1<T>
{
    public:
      T2(int t) : m_t(t) {} // error

      int get()
      { return this->m_t; }

    protected:
};

【问题讨论】:

    标签: c++ class templates inheritance constructor


    【解决方案1】:

    你需要在T2的初始化列表中调用基类构造函数:

    T2(int t) : T1<T>(t) {}
    

    T2&lt;T&gt;的构造函数会调用T1&lt;T&gt;的构造函数,它会初始化T1&lt;T&gt;::m_t

    【讨论】:

      猜你喜欢
      • 2016-03-04
      • 2019-12-14
      • 2019-12-14
      • 2023-01-15
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      相关资源
      最近更新 更多