类模板,无效空指针(字符串)

时间:2014-11-17 20:01:49

标签: 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";
}

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

1 个答案:

答案 0 :(得分:2)

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{}; 

(我还活着过去......)