2

我遇到了返回值/引用的问题。我正在编写一个模板(队列),并且Front()函数应该从队列的前面返回元素,但我得到一个错误 - No viable conversion from 'Queue<int>::Node' to 'const int'。当我删除时const,我得到Non-const lvalue reference to type 'int' cannot bind to a value of unrelated type 'Queue<int>::Node'了,而其他参考/无参考变体,const/no const 给了我这两个错误中的任何一个。我错过了什么?

#include <iostream>

using namespace std;

template <typename T>
class Queue
{
    friend ostream& operator<< (ostream &, const Queue<T> & );
private:
    class Node
    {
        friend class Queue<T>;
    public:
        Node(const T &t): node(t) {next = 0;}
    private:
        T front;
        T back;
        T node;
        Node *next;
    };
    Node *front;
    Node *back;
public:
    Queue() : front(0), back(0) {}
    ~Queue();
    bool Empty()
    {
        return front == 0;
    }
    T& Front()
    {
        if (Empty())
            cout << "Очередь пуста." << endl;
        else
        {
            T const & temp = *front; // error here
            return temp;
        }
    }
    /* ... */
};

template <class T> ostream& operator<< (ostream &, const Queue<T> & );

int main()
{
    Queue<int> *queueInt = new Queue<int>;
    for (int i = 0; i<10; i++)
    {
        queueInt->Push(i);
        cout << "Pushed " << i << endl;
    }
    if (!queueInt->Empty())
    {
        queueInt->Pop();
        cout << "Pop" << endl;
    }
    queueInt->Front();
    return 0;
}
4

2 回答 2

0

您的Node类定义没有多大意义:现在,每个节点存储 3 个数据值frontbacknode. 类应该是三元组的队列吗?

然而,在您的Front()函数中,您需要返回前端节点的“有效负载”(即返回类型T的东西),而不是节点本身。像这样的东西:

T& Front()
{
    if (Empty())
        cout << "Очередь пуста." << endl;
    else
    {
        return front->node;
    }
}
于 2013-03-23T09:43:48.523 回答
0

代替

T const & temp = *front;

T& temp = front->front;

Queue<T>::front是指向 a 的指针Node,换句话说,*front是 a Node。然后您尝试将 a 分配Node给 a T& const,因为编译器无法转换NodeT它会抱怨。现在,Node有一个成员也称为frontwhich is T,我这就是您想要返回的内容,这就是修复程序所做的。(可能你想回来front->node。我不清楚你的意图。)

In addition, you declared temp as T const & and Front returns it. However, the type returned by Front is T& (non nonst) and the compiler cannot convert from const to non-const. By declaring temp non-const (as in the fix) such conversion is no longer required.

于 2013-03-23T10:03:13.423 回答