c++ - 我的类函数的段错误

标签 c++ segmentation-fault singly-linked-list

所以我在这里的函数中遇到了段错误,我不确定如何更正它。关于我将如何去做的任何线索? 我包括我的类(class),然后是下面的功能,以了解我所拥有的。 谢谢!

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

最佳答案

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

其次是

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

是个问题。

您还没有为 result 分配内存并继续使用它,就好像它指向一个有效对象一样。

简化它。完全删除 result 并将 return 语句更改为:

return {x, y};

关于c++ - 我的类函数的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601225/

相关文章:

c++ - 使用指针与对象访问成员函数

c++ - 如何从 boost::thread 取回值?

c - gcc -O 段错误

c - 递归段错误和 StackGuard

c++ - 如何使链接列表按字母顺序打印出其内容?

python - Python 中的链表实现错误

c++ - C++ 中的析构函数和 delete() 方法

c++ - 从 Qt::Key 到 native 键盘代码

javascript - 为什么我在 Node.js 中出现段错误?

c++ - 指针似乎无缘无故地重新设置