1
votes

So, i have class ArrayList, and inside, i have class iterator. I tried everything to make operator<< inside iterator class, to work with iterators, but nothing works. I tried with and without friend, in private and public, inline and outside the class, i have nothing else to try so if someone has some suggestion, feel free to say :D tyyy

also, i don't know does it have something with my problem, but ArrayList is template class

template <typename T>
std::ostream& operator<<(std::ostream& os, const ArrayList<T>::iterator & it)
{
    return os << *it;
}

template <typename T>
class ArrayList {
private:
    T* elements_;
    size_t size_;
    size_t capacity_;
public:
class iterator;
};

template <typename T>
class ArrayList<T>::iterator {
private:
    T* ptr_;
public:
friend std::ostream& operator<<(std::ostream&, const iterator&);
};
2
Show us what you have tried so far - NutCracker
This should be straightforward, so show us an example of what you have tried. You are obviously making some mistake, but it's hard to know what it is without seeing your code. - john
Please provide some snippeds of code - armagedescu

2 Answers

1
votes

ArrayList<T>::iterator is a dependent name so it needs to be preceeded with typename keyword like:

template <typename T>
std::ostream& operator<<(std::ostream& os, const typename ArrayList<T>::iterator & it) {
//                                               ^^^
    return os << *it;
}

and, of course, your operator<< overload should be defined after your class definition.

Demo

UPDATE

In order to resolve linking errors mentioned in the comments, try placing the operator<< overload body directly into the class body like:

template <typename T>
class ArrayList<T>::iterator {
private:
    T* ptr_;
public:
    friend std::ostream& operator<<(std::ostream& os, const iterator& it) {
        return os << *it;
    }
};
0
votes

I would rather consider having operator *

template <typename T> class ArrayList {
private:
    T* elements_;
    size_t size_;
    size_t capacity_;
public:
    class iterator {
    private:
        T* ptr_;
    public:
        T operator *() {return *ptr_;}
    };
};

Now the operator << will work naturally for any type T that has operator defined, so you don't have to define it by yourself:

cout<< *it<< endl;

You will define the operator << only on typename T if it does not have operator defined. Normally you will not define it for int, char, string and so on.