ppanish
ppanish

Reputation: 3

C++ ostream operator overloading using const argument error

I'm trying to use the standard format for non-member function overloading for the ostream operator, but it will not work with a const second argument when I have an internal assignment to a vector iterator. The compiler gives the following error when a const argument is used: error: no match for 'operator=' in j = bus.owAPI::owBus::owCompList.std::vector...

Relevant parts of my Class are as follows:

class owBus{
    public:
        std::vector<owComponent> owCompList;    //unsorted complete list
        friend std::ostream& 
            operator<<(std::ostream& os, const owBus& bus );
};

with the non-member function:

std::ostream& operator<<(std::ostream& os, const owBus& bus ) {
    //iterate through component vector
    std::vector<owComponent>::iterator j;
    for(j=bus.owCompList.begin(); j!=bus.owCompList.end(); j++) {
    /*
        os << (*j).getComponentID() << ": ";
        os << (*j).getComponentType() << std::endl;
    */
    }
    return os;
}

This works fine if the const is removed from the friend declaration and the second argument in the function description, otherwise it give the error described above. I don't have an assignment operator defined for the class, but it's not clear to me why that should make a difference.

Upvotes: 0

Views: 795

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126175

That's because you're trying to use a non-const iterator to iterate through a const object. Change the declaration of j to:

std::vector<owComponent>::const_iterator j;

or just use the C++11 style:

for (auto j : bus.owCompList) {

Upvotes: 0

Related Questions