【问题标题】:Custom Assignment Operator and Iterators自定义赋值运算符和迭代器
【发布时间】:2013-04-03 01:53:26
【问题描述】:

我遇到了基本运算符重载的问题。我正在使用以下课程:

template <class T> 
class Node
{
    public:
        Node() {value = NULL; next = NULL; prev = NULL;}
        T* value;
        Node* next;
        Node* prev;   
};    


class fixedList
{
public:
    class fListIterator
    {
    public:
        Node<T>* point;
        fListIterator & operator=(Node<T>* x) {point = x; return this}
    };

    Node<T>* first;
    Node<T>* last
   fListIterator begin() {fListITerator a = first; return a;}
}

template <class T> fixedList<T>::fixedList(int x, T y)
{
     Node<T> data[x];

     for (int z = 0; z < x; z++)
     {
         data[0].value = &y;
     }

     first = &data[0];
     last = &data[x-1];

     Node<T>* assign = first;

     for (int i = 0; i < x - 1; i++)
     {
         Node<T>* temp = new Node<T>;
         temp = &data[i];
         assign->next = temp;
         assign->next->prev = assign;
         assign = assign->next;
     }

}

int main(int argc, char** argv) 
{
    fixedList<int>* test = new fixedList<int>(5, 2);
    fixedList<int>::fListIterator a = test->begin();

    return 0;
}

我不断收到 begin() 函数中的错误: “请求从 'Node*' 转换为非标量类型 'fixedList::fListIterator'”

谁能弄清楚我做错了什么?

编辑: 抱歉,我试图保持紧凑。

【问题讨论】:

  • 显示test的声明和Node的类定义。
  • 编译器指出根本问题所在的行也会有所帮助(如果您可以在问题中标记它)。

标签: c++ iterator variable-assignment operator-keyword


【解决方案1】:

当您在等号运算符中返回 this 时,程序会尝试返回您从中调用它的 Node*(因为它接受 Node&lt;T&gt;* 作为参数)。

【讨论】:

  • 我如何让它返回对象呢?
  • 在我看来,您希望函数返回 fixedList::fListIterator* 而不是 Node&lt;T&gt;*,因此请尝试将其更改为该函数。我认为当您调用 test-&gt;begin()(从 fListIterator 到 Node*)时可能会发生隐式转换,这就是您在该位置遇到问题的原因。
【解决方案2】:

fListIterator begin() {fListITerator a = first; return a;}

语句fListITerator a = first; 是一个构造。您正在尝试调用 fListIterator 的构造函数,将 Node&lt;T&gt;* 作为参数 - 除非您没有!

如果您在两个语句中破坏此代码:

fListIterator begin() {fListITerator a; a = first; return a;}

它会:

  • 使用fListIterator的默认构造函数构造a(由于您没有显式提供构造函数,编译器会自动为您生成一个);
  • 使用operator= 重载将first 分配给a
  • 正确返回a

但是,您应该小心:正如 user1167662 的答案所指定的那样,您的 fListIterator::operator= 没有返回正确的值。 this,在这种情况下,是 fListIterator* 类型。

【讨论】:

    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2018-09-18
    • 2011-11-16
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多