C ++ перегружен << операция только печатает адрес памяти LinkedList - PullRequest
0 голосов
/ 17 октября 2018

Я пытаюсь создать LLC контейнера связанных ссылок и перегрузить оператора << как друга.Кажется, что не важно, что я делаю, он либо печатает адрес памяти, либо выдает ошибку сегментации.Я еще не совсем понимаю c ++, так что это, вероятно, что-то очевидное. </p>

в 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 голосов
/ 17 октября 2018

std::ostream уже имеет operator<<, который принимает указатель (через void*) в качестве ввода.Вот почему вы получаете шестнадцатеричный вывод.Ваша перегрузка operator<< должна принимать объект 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;
}
...