0

这是我的 HeapNode 模板类定义:

#ifndef HEAP_N

#define HEAP_N

template <class T>
class HeapNode{

public:
    // Constructor
    HeapNode(T item = T(), int new_freq = 0, int new_right = 1, 
             int new_left = 1, int new_parent = 1);

    // Accessor Functions
    T data();
    int frequency();
    int right_child();
    int left_child();
    int parent();

    // Mutator Functions
    void set_data(T item);
    void set_frequency(int new_freq);
    void set_right(int new_right);
    void set_left(int new_left);
    void set_parent(int new_parent);

    // Operators
    HeapNode operator =(const HeapNode& other);
    bool operator >(const HeapNode& other);

private:
    T datafield;    // contains the data of the node
    int freq;       // frequency
    int l_child;    // index of left child
    int r_child;    // index of right child
    int parent_;    // index of parent
};

#include "HeapNode.template"

#endif

这些分别是 mutator 和 accessor 函数:

template <class T>
void HeapNode<T>::set_data(T item){
    datafield = item;
}

template <class T>
T HeapNode<T>::data(){
    return(datafield);
}

这是进行函数调用的函数:

void insert_or_update(string value, Heap<HeapNode<string> >& heap){ 

    HeapNode<string> temp;
    temp.set_data(value);
    temp.set_frequency(1);

        string ex = temp.data(); // The seg fault actually occurs in the find() function below, but any attempt to get temp.data() seg faults so the location is irrelevant

    if(!heap.empty()){  
        int index = heap.find(temp);
        if(index != -1){
            heap.inc_frequency(index);          
        }
        else{
            heap.insert(temp);
        }
    }
    else{
        heap.insert(temp);
    }   
}

段故障发生在

string ex = temp.data(); 

线。

这些函数适用于非字符串对象,但是当我使用字符串(常量字符串和变量字符串,两者)时会出现段错误。

我尝试使用实现

datafield = item;

使用复制构造函数的行:

datafield = T(item);

但这也没有用。既没有通过引用传递,也没有设置

datafield

成为公共成员并直接更改它。

注意:这必须在 C++ 98 编译器上编译,所以我不能使用字符串移动功能!

如果您需要更多信息,请告诉我。

非常感谢!

4

0 回答 0