baidu_18272515 2020-08-19 23:05 采纳率: 50%
浏览 178
已结题

C++抽象类模板实例化报错

报错:seqStack不能实例化抽象类?
应该如何修改才能正确运行?

#pragma once
#include "seqStack.hpp"
#include "Stack.hpp"
#include <iostream>

/*
    用数组实现栈,实现pop与push,支持扩容保证性能
*/

using namespace std;

template<class T>
seqStack<T>::seqStack(T initSize)
{
    if (initSize <= 0)
    {
        throw badSize();
        data = new T(initSize());
        maxSize = initSize;
        top = -1;
    }
}

template<class T>
seqStack<T>::~seqStack()
{
    delete[] data;
}

template<class T>
bool seqStack<T>::empty() const
{
    return top == -1;
}

template<class T>
int seqStack<T>::size() const
{
    return top + 1;
}

template<class T>
void seqStack<T>::clear() const
{
    top = -1;
}

template<class T>
void seqStack<T>::push(const T &value) {
    if (top == maxSize - 1)
    {
        resize();
    }
    data[++top] = value;
}

template<class T>
T seqStack<T>::pop() {
    if (empty())
    {
        throw OutOfRange();
    }
    return data[top--];
}

template<class T>
T seqStack<T>::getTop() const{
    if (empty())
    {
        throw OutOfRange();
        return data[top];
    }
}

template<class T>
void seqStack<T>::resize() {
    T * tmp = data;
    data = new T[2 * maxSize]; //申请双倍空间
    for (int i = 0; i < maxSize; i++)
    {
        data[i] = tmp[i];
    }
    maxSize *= 2;
    delete[] tmp;
}

int main() {
    seqStack<int> s(100);
    system("pause");
    return 0;
}
#pragma once
#include "Stack.hpp"

template <class T>
class seqStack : public Stack<T> {
private:
    T * data;
    int top;
    int maxSize;
    void resize();

public:
    seqStack(T initSize = 100);

    ~seqStack();

    bool empty() const;

    int size() const;

    void clear() const;

    //入栈
    void push(const T &value);

    //出栈
    T pop();

    //获取栈顶元素
    T getTop() const;
};
#ifndef __STACK_H_
#define __STACK_H_
#include <exception>
using namespace std;

//定义模板抽象类
template <class T>
class Stack {
public:
    //纯虚函数
    virtual bool empty() const = 0;
    virtual int size() const = 0;
    virtual void push(const T &x) = 0;
    virtual T pop() = 0;
    virtual T getTop() const = 0;
    virtual void clear() = 0;
    virtual ~Stack();

private:

};

/*
    定义自己的异常类,C++11后不再使用
*/

//检查是否越界
class OutOfRange : public exception {
public:
    const char * what() const throw() {
        return "Error! out of range.\n";
    }
};

//用于检查长度的有效性
class badSize : public exception {
public:
    const char * what() const throw() {
        return "Error! Bad Size.\n";
    }
};

#endif // !__STACK_H_

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?