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