STL & Overload in C++

STL & Overloading in C++

本文关键字:C++ in Overload STL      更新时间:2023-10-16

我创建了一个由节点组成的双链接列表。我在STL工作。我在operator++函数中得到一个错误。这是我的Iterator<T>课程。

#include "Node.h"
#include <iostream>
using namespace std;
template<class T> class Iterator{
public:
    Iterator();
    ~Iterator();
    Node<T> *node;
    void operator++(Iterator<T> val);
    void operator--();
    T operator*();
private:
};
template<class T>
Iterator<T>::Iterator(){
    node = 0;
}
template<class T>
Iterator<T>::~Iterator(){
}
template<class T>
void Iterator<T>::operator++(Iterator<T> val){
    if(node != 0){
        node = node->next;
    }
}
template<class T>
void Iterator<T>::operator--(){
    if(node != 0)
        node = node->prev;
}
template<class T>
T Iterator<T>::operator*(){
    if(node == 0){
        cout << "Node no exists!";
    }
    else{
        return node->value;
    }
}

我的main函数中也收到了警告。

#include <iostream>
#include "List.h"
using namespace std;
int main()
{
    List<int> mylist;
    for(int i = 2; i < 10; i++){
        mylist.push_back(i);
    }
    Iterator<int> it = mylist.begin();
    while(it.node->next != 0){
        cout << it.node->value << "n";
        it++;
    }

    mylist.pop_front();
    cout << mylist.front() << ", ";
    cout << mylist.back();
    return 0;
}

错误和警告

F: \新文件夹\C++\Lab14\Iterator.h||在'class的实例化中迭代程序':|

F: \新文件夹\C++\Lab14\main.cpp|15|此处需要|

F: \新文件夹\C++\Lab14\Iterator.h|29|错误:postfix'void"Iterator::operator++(Iterator([with T=int]"必须取"int"作为其论据|

F: \新文件夹\C++\Lab14\main.cpp||在函数'int main(('中:|

F: \新文件夹\C++\Lab14\main.cpp|19|错误:没有"operator++(int("为后缀"++"声明[-fpermission]|

顺便说一句,我也计划对其他运营商做同样的事情。operator*不适用于乘法运算。

operator++必须采用单个int或不采用参数:

void operator++(int);
void operator++();

第一个是后缀++的过载,第二个是前缀++的过载。int参数只是为了允许发生正确的过载;其值未指定。

您的operator++申报目前如下:

void operator++(Iterator<T> val);

您似乎期望将递增的对象作为参数传递。实际上,对象就是this所指向的对象。您可以这样实现operator++

template<class T>
Iterator<T> Iterator<T>::operator++(int) {
    Iterator<T> copy = *this;
    if(node != 0) {
        node = node->next;
    }
    return copy;
}

请注意,在更改对象的node成员之前,我还返回了该对象的副本。这通常是后缀增量运算符所期望的。

若要获得前缀增量,请不带参数重载。它应该通过引用返回*this。即。迭代运算符++(int(;//后缀迭代程序&运算符++((;//前缀

与大多数运算符一样,有两种方法可以定义operator++。您可以将它作为迭代器类的成员编写,也可以作为一个自由函数编写。但还有另一个复杂的问题,因为operator++有两种形式:前缀和后缀。所以写这个操作符需要更多的思考。

作为会员:

struct Iterator {
    Iterator& operator++();   // prefix
    Iterator operator++(int); // postfix
};

作为免费功能:

struct Iterator { };
Iterator& operator++(Iterator&);     // prefix
Iterator operator++(Iterator&, int); // postfix

operator++不应该接受参数。从原型和定义中删除参数应该可以修复您的错误。

就像一个小的">指针"(明白吗?(一样,解引用运算符可能应该返回node<T>,而不是T。(两者都可以,但前者更有意义,使其行为方式与std容器类似。(