C++ 覆盖模板 class 模板 class 中的虚函数

C++ Override Template class virtual function in Template class

我试图用下面的方法覆盖我程序中的函数,但在编译时它在派生清除函数中显示变量 1 为未定义。

在将派生的 class 更改为非模板时,我已经能够使它工作,但是在为 Base 启动模板时我缺少 DATATYPE 和 VALUE 变量。

template <class DATATYPE=short, short VALUE = 100>
class Base {
    public:
    Base();

    virtual void clear()=0;
    
    protected:
    int variable1;
}


template <class DATATYPE=short, short VALUE = 100>
class Derived : public Base<DATATYPE, VALUE> {
    public:
    Derived();

    void clear() {
        int testVar = variable1;
    }
}

您的代码的编译版本:

template <typename data_t, short value_v>
class Base 
{
public:
    Base() = default;               // <== was missing impl, set to default
    virtual ~Base() = default;      // classes with virtual methods must have virtual destructor
    virtual void clear() = 0;

protected:
    int variable1;
}; 


template <typename data_t = short, short value_v = 100>
class Derived : 
    public Base<data_t, value_v>
{
    // by adding a using you can more easily change the template params
    // without having to update all your code. Helps keeping code more readable too
    using base_t = Base<data_t, value_v>;

public:
    void clear() override // <== missing override
    {
        //  different ways of accessing member in template base class
        int v1 = Base<data_t, value_v>::variable1;
        int v2 = this->variable1;
        int v3 = base_t::variable1;
    }
}; 


int main()
{
    Derived<short,100> d;
    d.clear();
}