重载的链式运算符<<缓冲输出

时间:2018-01-31 12:19:35

标签: c++ operator-overloading

我有一个简单的类LinkedList,它有重载的流插入和索引操作符。

LinkedList.h

#pragma once
#include <functional>
#include <vector>
#include <ostream>

namespace linkedlist
{
    class LinkedList
    {
        friend std::ostream& operator<<(std::ostream&, const LinkedList&);

        struct Node;
        Node *head;
        int n;

        struct Node
        {
            double data;
            Node *next;

            Node(double data) : data(data), next(nullptr) {} 
        };

    public:
        LinkedList() = default;
        ~LinkedList();

    public:
        LinkedList& add(double);
        const double& operator[](int index) const;
        double& operator[](int index);
    };
}


LinkedList.cpp

#include "LinkedList.h"

namespace linkedlist
{
    LinkedList::~LinkedList()
    {
        while (head)
        {
            Node *toDelete = head;
            head = head->next;
            delete toDelete;
        }

        head = nullptr;
    }

    LinkedList& LinkedList::add(double data)
    {
        Node *newNode = new Node(data);

        if (head == nullptr)
            head = newNode;

        else 
        {
            Node *temp = head; 

            while (temp->next)
            {
                temp = temp->next;
            }
            temp->next = newNode; 
        }

        n++;
        return *this;
    }

    const double& LinkedList::operator[](int index) const
    {
        Node *temp = head;

        while (--index)
            temp = temp->next;

        return temp->data;
    }

    double& LinkedList::operator[](int index)
    {
        Node *temp = head;

        while (index-- > 0)
            temp = temp->next;

        return temp->data;
    }


    std::ostream& operator<<(std::ostream& stream, const LinkedList& list)
    {
        for (LinkedList::Node *temp = list.head; temp != nullptr; temp = temp->next)
            stream << temp->data << " ";

        return stream;
    }

}

两个操作员功能都经过测试并且运行正常。

但是,当进入主要功能的最后一行

int main()
{
    LinkedList A;
    A.add(3).add(2).add(5).add(7);

//  cout << A << endl;     // works!
//  cout << A[0] << endl;  // works!
    cout << A[0] << " " << A[1] << " " << A[2] << " " << A[3] << " " << endl;   
}

我注意到了流插入操作符的奇怪行为。

由于操作员的关联性即使在超载时也没有改变,我期望从左到右执行对operator[]的调用,并且在每个调用之后执行要打印的元素ostream 1}}返回引用(允许正确链接运算符)。

相反,操作员是从最右边的那个调用的

first visit to the operator[]

在连续四次调用operator[]之后,执行进入ostream类,并且元素已打印到控制台。

这是某种缓冲吗?为什么链式<<运算符表现得像这样?

0 个答案:

没有答案