【问题标题】:Template Class derived from Non-template base class: No access to base class variables?从非模板基类派生的模板类:无法访问基类变量?
【发布时间】:2014-03-13 01:56:27
【问题描述】:

我有以下类结构:

class Base {
public:
    std::set<Index> openIndices;
    Base() {};
};


template<typename lhs_t, typename rhs_t>
class Derived : public Base {
public:
    lhs_t &lhs;
    rhs_t &rhs;

    Derived(lhs_t &_lhs, rhs_t &_rhs) : 
            Base(), 
            lhs(_lhs),
            rhs(_rhs),
            openIndices(std::set_symmetric_difference(lhs.openIndices, rhs.openIndices)) 
    {
    }
};

所以基本上是一个模板类Derived派生自基类Base。访问基类的成员变量时,出现以下错误:

test.h:34:88: error: class ‘Derived<lhs_t, rhs_t>’ does not have any field named ‘openIndices’

我知道this question:如果我的类是从模板类派生的,我将无法访问成员变量。但在我的情况下,我不是从模板类派生的,我仍然无法访问成员变量。谁能告诉我为什么?

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    您不能初始化基类的成员变量。您必须在基类中提供适当的构造函数并调用此构造函数。

    【讨论】:

    • 天哪,是的,我应该知道这一点!显然,我对真实代码中的模板感到困惑。还是谢谢。
    猜你喜欢
    • 2019-11-09
    • 2016-08-17
    • 2012-09-12
    • 2016-02-02
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多