2017-04-25 46 views
1

所以我在這裏得到了我的功能分段錯誤,我不知道如何糾正它。任何線索,我會怎麼去呢? 我包括我的課程,然後下面的功能,以瞭解我有什麼。 謝謝!我的班級功能的分段錯誤

template <typename T> 
class Element{ 
private: 
    Element *next_ = nullptr; 
    string name_ = ""; 
    T color_ = T(); 

public: 
    Element()=default; 
    Element(string name, T d) : next_(nullptr), name_(name), color_(d){}; 
    friend ostream& operator<<(ostream& out, Element& n){ 


    out << n.name_ << ":" << n.color_; 
    return out; 

    } 
    friend class PAL<T>; 
}; 


template<typename T> 
class PAL{ 
private: 
    Element<T> *back_ = nullptr; 
    Element<T> *front_ = nullptr; 
    void print_list(ostream& out); 
public: 
    PAL()=default; 
    PAL(Element<T> n) : back_(&n), front_(&n) {}; 
    PAL(string n, T d); 
    PAL(const PAL&); 
    PAL& operator=(PAL); 
    ~PAL(); 
    void add(Element<T> &n); 
    void add(string name, T dat); 
    pair<Element<T>*, Element<T>*> find(string name);  
    pair<Element<T>*, Element<T>*> find(Element<T> &n); 
    void move_forward1(Element<T> &n); 
    void move_to_front(Element<T> &n); 
    void move_back1(Element<T> &n); 
    void move_to_back(Element<T> &n); 

    friend ostream& operator<<(ostream& out, PAL<T>& sl){ 
    sl.print_list(out); 
    return out; 
    }; 
}; 

template<typename T> 
pair<Element<T>*, Element<T>*> PAL<T>::find(string name){ 
    pair<Element<T>*, Element<T>*> *result (nullptr); 
    Element<T>* x = nullptr; 
    Element<T>* y = nullptr; 
    for (Element<T> *n = back_; n != nullptr; n = n -> next_){ 
     if (n -> name_ == name){ 
      x = n; 
      cout << x; 
      break; 
     } 
     y = n; 
    } 
    result -> first = x; 
    result -> second = y; 
    return *result; 
} 

回答

1
pair<Element<T>*, Element<T>*> *result (nullptr); 

隨後

result -> first = x; 
result -> second = y; 
return *result; 

是一個問題。

您還沒有爲result分配內存,並繼續使用它,就像它指向一個有效的對象一樣。

簡化它。刪除result乾脆改變return聲明:

return {x, y}; 
+0

神轉速r薩胡。 – javaLover

+0

@javaLover,Ha。 –

+0

啊哈!謝謝你:) – Alex