c++ - C++ 中的 STL 和重载

标签 c++ stl operator-overloading

我用节点创建了一个双向链表。我正在使用 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;

}

ERRORS AND WARNINGS

F:\New folder\C++\Lab14\Iterator.h||In instantiation of 'class Iterator':|

F:\New folder\C++\Lab14\main.cpp|15|required from here|

F:\New folder\C++\Lab14\Iterator.h|29|error: postfix 'void Iterator::operator++ (Iterator) [with T = int]' must take 'int' as its argument|

F:\New folder\C++\Lab14\main.cpp||In function 'int main()':|

F:\New folder\C++\Lab14\main.cpp|19|error: no 'operator++(int)' declared for postfix '++' [-fpermissive]|

顺便说一句,我也打算对其他运营商做同样的事情。 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。 IE。 迭代器运算符++(int);//后缀 迭代器和运算符++();//前缀

关于c++ - C++ 中的 STL 和重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15498745/

相关文章:

c++ - 跳过元素缓冲区中的索引

c++ - 如何对 SDL2 音频流数据执行实时 FFT

c++ - 从 vector 中调用派生类函数 (c++)

c++ - 如何使用 C++ std 计算整数集合的前导零和尾随零

c++ - 如何重载调用自身重载版本的函数?

Python重载变量赋值

c++ - 使用这个 "shortcutting function"是一个好习惯吗?

c++ - 插入到 STL 映射是否会使其他现有迭代器失效?

C++:访问可能不存在的 const vector 成员 - try/catch 或 if (count != 0)?

c++ - 模板结构中的重载运算符