程序不使用输出运算符

时间:2015-12-25 12:46:52

标签: c++ c++11

我目前正在开发一个应该是队列作为双向链表的程序。该程序有效,但我的问题是它没有使用输出运算符来“Queue_element”。它只使用标准输出运算符。我如何更改我将使用它的程序?

到目前为止,这是我的代码:

#include <iostream>

using namespace std;

template<typename T> class Queue;

template<typename T> class Queue_element {
private:
    T value;
    Queue_element<T>* next;
    Queue_element<T>* prev;

public:
    Queue_element() { value = 0; next = nullptr; prev = nullptr; }
    Queue_element(T n) { value = n; next = nullptr; prev = nullptr; }

    template<typename S> friend ostream& operator<<(ostream& os, const Queue_element<S>& queue_el);
    template<typename S> friend ostream& operator<<(ostream& os, const Queue<S>& queue);
    friend class Queue<T>;
};

template<typename T> class Queue {
private:
    Queue_element<T>* head;
    Queue_element<T>* tail;

public:
    Queue() { head = nullptr; tail = nullptr; }
    void push(T n);
    bool empty() const;

    template<typename S> friend ostream& operator<<(ostream& os, const Queue<S>& queue);
};

template<typename T> bool Queue<T>::empty() const
{
    if (this->head == nullptr && this->tail == nullptr) { return true; }
    else return false;
};

template<typename T> void Queue<T>::push(T n) {
    Queue_element<T>* q = new Queue_element<T>(n);
    if (this->empty()) { this->head = q; this->tail = q; }
    else { this->tail->next = q; q->prev = tail; this->tail = q; }
}

template<typename S>
ostream& operator<<(ostream& os, const Queue_element<S>& queue_el) {
    os << queue_el.value;
    return os;
}

template<typename S>
ostream& operator<<(ostream& os, const Queue<S>& queue){
    Queue_element<S>* q = queue.head;
    while(q != nullptr){
        os << q->value << " ";
        q = q->next;
    }
return os;
}

int main()
{
    Queue<string> q1;
    q1.push("test");
    cout << q1 << endl;
    return 0;
}

虽然这是输出操作员我在谈论:

template<typename S>
ostream& operator<<(ostream& os, const Queue_element<S>& queue_el) {
    os << queue_el.value;
    return os;
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

因为您没有使用输出操作符:

os << q->value << " ";

更改为

os << *q << " ";

答案 1 :(得分:3)

因为您隐式调用以下函数:

template <typename S>
ostream& operator<<(ostream& os, const S& queue_el_val)

使用

os << *q << " ";

代替。