如何定义泛型类型的静态变量

how to define a static variable of generic type

本文关键字:泛型类型 静态 变量 定义 何定义      更新时间:2023-10-16

我写了一个类如下:

template <class T>
/* Abstract class for stack n queue */
class StacknQueue
{
public:
    StacknQueue(int = 10);
    virtual int insert(const T&) = 0;
    virtual int remove(T&) = 0;
    virtual void display() = 0;
    int isEmpty() const {return top == -1 || front == -1 || front > top ;}
    int isFull() const { return top == size - 1 ;}
    //virtual int isQEmpty const() = 0;
    //virtual int isQFull const() = 0;
    void initialize();
    static int flag;
    static int size;
    //int rear;
    static int front;
    static int top;
    static T *stknqPtr ;
};

当我尝试在类外定义变量stknqPtr时,如下所示:

template <class T>
    T StacknQueue<T> :: stknqPtr = new T[size];

显示错误:

error C2040: 'stknqPtr' : 'float' differs in levels of indirection from 'float *'

我是一个c++新手,谁能告诉我怎么做?

Thanks in advance

您的定义类型错误。它没有定义指针。应该是:

template <class T>
T* StacknQueue<T>::stknqPtr = ...;

您需要使其成为正确的类型-在类中是T*,但在定义中是T

但是——你的类设计建议它的所有成员不应该是静态的——否则每个实例都将共享相同的后台数据——这不是你通常想要的堆栈或队列。对于非静态成员,您不需要恼人的显式实例化-因此一切都变得简单。