C ++重载<<操作仅显示LinkedList

时间:2018-10-17 16:45:05

标签: c++ linked-list operator-overloading nodes

我试图制作一个链接列表容器LLC,并将<<操作符重载为朋友。看来我所做的一切都没问题,要么打印内存地址,要么抛出分段错误。我还不太了解c ++,所以它可能很明显。

在LLC.cpp中

ostream& operator<<(ostream& os, const LLC* list){
   Node *curr = list.first;
   for(curr; curr != NULL; curr= curr -> next){
   os << curr -> data << "\n";
}
return os;
}

int main(int argc, char *argv[]){
  string arr [] = {"a","b","c","d","e","f"};
  LLC* link = new LLC(arr);
  cout<<"testing: ";
  cout<<(link);
}

在LLC.h

struct Node {
 std::string data;
 Node *next;
};
class LLC {

private:
  Node *first;
  Node *last;
public:
    int main(int argc, char *argv[]);
    LLC(){
      first=NULL;
      last=NULL;
    }
    friend std::ostream& operator<<(std::ostream& os, const LLC*);

1 个答案:

答案 0 :(得分:0)

std::ostream已经有一个operator<<,它使用一个指针(通过void*)作为输入。这就是为什么您得到十六进制输出的原因。您的operator<<重载应通过const引用而不是const指针接收LLC对象,以避免产生歧义。

您没有发布足够的代码来演示segfault错误,但是我怀疑这是因为您没有在列表中正确管理节点实例,因此当您的operator<<尝试访问它们时,它遇到了问题指针沿途崩溃。

尝试更多类似的方法:

LLC.h

#ifndef LLCH
#define LLCH

#include <iostream>
#include <string>

struct Node {
    std::string data;
    Node *next;

    Node(const std::string& d);
};

class LLC {
private:
    Node *first;
    Node *last;

public:
    LLC();

    template<size_t N>
    LLC(std::string (&arr)[N])
        : first(NULL), last(NULL) {
        for(size_t i = 0; i < N; ++i) {
            addToBack(arr[i]);
        }
    }

    // other constructors, destructor, etc...

    void addToBack(const std::string &s);

    // other methods ...

    friend std::ostream& operator<<(std::ostream& os, const LLC& list);

    // other operators ...
};

#endif

LLC.cpp

#include "LLC.h"

Node::Node(const std::string& d)
    : data(d), next(NULL) {
}

LLC::LLC()
    : first(NULL), last(NULL) {
}

// other constructors, destructor, etc...

void LLC::addToBack(const std::string &s) {
    Node *n = new Node(s);
    if (!first) first = n;
    if (last) last->next = n;
    last = n;
}

// other methods ...

std::ostream& operator<<(std::ostream& os, const LLC& list) {
    for(Node *curr = list.first; curr != NULL; curr = curr->next) {
        os << curr->data << "\n";
    }
    return os;
}

// other operators ...

Main.cpp

#include <iostream>
#include <string>
#include "LLC.h" 

int main(int argc, char *argv[]) {
    std::string arr[] = {"a", "b", "c", "d", "e", "f"};

    LLC* link = new LLC(arr);
    cout << "testing: " << *link;
    delete link;

    /* or simply:
    LLC link(arr);
    cout << "testing: " << link;
    */

    return 0;
}