【问题标题】:How to instantiate an object inheriting from a pure virtual class that uses templates如何实例化从使用模板的纯虚拟类继承的对象
【发布时间】:2020-02-03 20:29:21
【问题描述】:

我正在创建一个“Array_Base”接口,允许用户创建固定数组或任何类型的可扩展数组。现在我什至无法让常规 Array 工作。

我已将问题分解为几个最简单的组件,以尝试隔离问题。我相信这与我的实例化有关。我正在使用 Visual Studio 运行代码。

Array_Base.h

#ifndef _ARRAY_BASE_H_
#define _ARRAY_BASE_H_
#include <cstring>          // for size_t definition

template <typename T>
class Array_Base 
{
public:
        typedef T type;
    //Default Constructor
    virtual void Array_Base(void) = 0;

    // Destructor.
    virtual ~Array_Base(void) = 0;

protected:
    /// Pointer to the actual data.
    T* data_;

    /// Current size of the array.
    size_t cur_size_;

    /// Maximum size of the array.
    size_t max_size_;
};

#endif   // !defined _ARRAY_H_

数组.h

#ifndef _ARRAY_H_
#define _ARRAY_H_
#include <cstring>          // for size_t definition
#include "Array_Base.h"

template <typename T>
class Array : public Array_Base
{
    public:
    /// Type definition of the element type.
    typedef T type;

    /// Default constructor.
    Array (void);

        ///Destructor
    ~Array (void);
};

#include "Array.cpp"
#include "Array.inl"
#endif   // !defined _ARRAY_H_

数组.cpp

#include <stdexcept>         // for std::out_of_bounds exception
#include <iostream>
#define MAX_SIZE_ 20

template <typename T>
Array <T>::Array (void)
        :data_(new T[MAX_SIZE_]),
    cur_size_(0),
    max_size_(MAX_SIZE_)
{       }

template <typename T>
Array <T>::~Array (void)
{
    delete[] this->data_;
    this->data_ = nullptr;
}

Main.cpp:

#include "Array.h"

int main(void)
{   
    Array_Base<int>* arr = new Array<int>();
        delete arr;
}

我不断收到一条错误消息:“值类型“Array”不能用于初始化“Array_Base”类型的实体,从出现在“new”运算符下方的红线中主要。

任何帮助将不胜感激。谢谢!

【问题讨论】:

标签: c++ templates inheritance interface


【解决方案1】:
template <typename T>
class Array : public Array_Base

Array_Base 没有命名类。您需要为其提供模板参数。

你是这个意思吗?

template <typename T>
class Array : public Array_Base<T>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2013-10-07
    相关资源
    最近更新 更多