简体   繁体   English

C ++模板实例化指针空错误

[英]C++ template instantiation pointer null error

I want to write my own version of stack, this is what I have: 我要编写自己的堆栈版本,这就是我的意思:

template<class myStackType> class myStackClass
{
    myStackType array[1000];
    int size;
public:
    myStackClass()
    {
        size = 0;
    }
    void pop()
    {
        size--;
    }
    void push(myStackType a)
    {
        array[size] = a;
        size++;
    }
    myStackType top()
    {
        return array[size-1];
    }
    bool empty()
    {
        return(size == 0);
    }
};

but when I try to actually use it 但是当我尝试实际使用它时

struct grade
{    
    int mid;
    int final;
    string name;
    grade(int mid1 = 0, int final1 = 0, string name1 = 0)
    {
        mid = mid1;
        final = final1;
        name = name1;
    }
};

myStackClass<grade> myStack;

I get a debug assertion failed: invalid null pointer 我收到调试断言失败:无效的空指针

on the other hand, the std::stack works just fine in the same spot with the same data type 另一方面,std :: stack在具有相同数据类型的相同位置上也可以正常工作

what am I doing wrong? 我究竟做错了什么?

Thanks! 谢谢!

This is wrong: 这是错误的:

string name1 = 0

It tries to construct a string from a const char* which is 0 - and this is not allowed. 它尝试从const char*构造一个string ,该string0不允许这样做。 You probably meant: 您可能的意思是:

string name1 = ""

You are assigning 0 to a string in your constructor. 您正在将0分配给构造函数中的字符串。 That's the bug. 那是错误。 The compiler is trying to interpret the 0 as a char *, ie a C-style string. 编译器试图将0解释为char *,即C样式的字符串。 But since it's a 0, it is interpreted as a NULL pointer. 但是由于它是0,所以将其解释为NULL指针。

You may also want to do some error checking to make sure your stack doesn't overflow, or that you don't try to pop off an empty stack. 您可能还需要进行一些错误检查,以确保堆栈不会溢出,或者不要尝试弹出空堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM