简体   繁体   中英

Defining operator overload on pointer

Given

struct foo {
    struct node {
        int data;
        node* next, prev;
    };
    friend std::ostream& operator<< (std::ostream& os, const foo::node& n) {
         os << n.data;  
         return os;
    }
    // friend node* operator++ (list::node* n) { return n->next; }
};

I need to overload ++ that acts on foo::node* only. Where and how do I define that operator? My commented-out line above indicates what I'm trying to do. Thanks.

An example usage is:

for (list::node* it = f.begin();  it != f.end();  ++it)
     std::cout << *it << ' ';

where f is a foo object, and the begin() and end() functions return some foo::node pointers.

C++ doesn't allow you to define operator overloads for primitive types. In this case, foo::node* is primitive type.

What you can do is create your own wrapper around foo::node* which behaves as you desire:

struct node_iterator
{
    foo::node* _p;

    // ...

    friend node_iterator operator++(node_iterator n) 
    { 
        return {n._p->next}; 
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM