c++ - 类模板,无效的空指针(字符串)

标签 c++ templates pointers null

创建了一个模板类,它符合并可以很好地使用整数运行,当我尝试使用字符串运行时,我收到无效的空指针错误。

我只在创建堆的方法中添加,也就是发现错误的地方。

//heap.h
#include <iostream>
#include <vector>
using namespace std;

template<class TYPE>
class Heap{
private:

    vector<TYPE> heap;
    int size;// number of elements in the heap
    bool maxheap = true;//default value
    TYPE bubble_up(TYPE item);
    TYPE bubble_down(TYPE item);

public:

    Heap();
    Heap(bool maxheap);
    Heap(vector<TYPE>, bool order);
    ~Heap();
    void build_heap();
    TYPE Insert(TYPE item);
    TYPE Delete(TYPE& item);
    const vector<TYPE> sort(bool order);
    const vector<TYPE> sort();// defualt sort if no variable given, max sort
    TYPE get_size();
    void print_heap();
    void clear_heap();
};

template<class TYPE>
Heap<TYPE>::Heap(){
    TYPE dummy = 0;
    heap.push_back(dummy);
    size = heap.size() - 1;
}

template<class TYPE>
Heap<TYPE>::Heap(bool order){
    maxheap = order; // true is max, false is min
    TYPE dummy = 0;
    heap.push_back(dummy);
    size = heap.size() - 1;

}

template<class TYPE>
Heap<TYPE>::Heap(vector<TYPE> x, bool order){
    maxheap = order;// true is max, false is min
    TYPE tempSize;
    TYPE dummy = 0;
    heap.push_back(dummy);
    size = heap.size() - 1;
    tempSize = x.size();
    for (TYPE y = 0; y < tempSize; y++){
        heap.push_back(x[y]);
    }
    size = heap.size() - 1;
    build_heap();
}

我已经删掉了接下来几行代码中发现问题的部分。

//driver.cpp
#include <iostream>
#include <string>
#include "Heap.h"

using std::cout;
using std::endl;

typedef string TYPE;

int main(void) {

    Heap<std::string> *s_heap = new Heap<std::string>();  // string heap
    std::string s_item = "0";
}

“调试断言失败!” “表达式:无效的空指针”

最佳答案

template<class TYPE>
Heap<TYPE>::Heap(){
    TYPE dummy = 0;
    heap.push_back(dummy);
    size = heap.size() - 1;
}

第一行将翻译为:

 std:string dummy = 0;

我认为您不能将字符串设置为零。

尝试将其更改为:

TYPE dummy = TYPE();

更新: 正如 juanchopanza 指出的那样,现代语法是:

TYPE dummy{}; 

(我还活在过去……)

关于c++ - 类模板,无效的空指针(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26980936/

相关文章:

c - 在c中修改char指针的值会产生段错误

c++ - 如何适本地将指针设置为新结构?

c++ - 分层接口(interface)和实现

c++ - 在模板类中使用 lambda

c++ - 模板模板和部分特化 : a puzzle

HTML 元素在一个或另一个中连续为 "nesting"

delphi - 在德尔福/自由帕斯卡 : is ^ an operator or does it simply denote a pointer type?

c++ - 多级继承和纯虚函数

c++ - 什么会导致 D3D11CreateDevice() 因 E_FAIL 而失败?

C++初始化常量和继承