【问题标题】:Segmentation fault on my class function我的类函数的分段错误
【发布时间】:2017-09-21 21:50:55
【问题描述】:

所以我在这里的函数出现分段错误,我不知道如何纠正它。关于我将如何去做的任何线索? 我包括我的课程,然后是下面的函数,以了解我所拥有的。 谢谢!

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

【问题讨论】:

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


    【解决方案1】:
    pair<Element<T>*, Element<T>*> *result (nullptr);
    

    紧随其后

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

    是个问题。

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

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

    return {x, y};
    

    【讨论】:

    • 神速R萨胡。
    • @javaLover, Ha.
    • 啊哈!谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2014-11-05
    相关资源
    最近更新 更多