简体   繁体   中英

How to overload ostream operator<< for a pimpl class?

This is what I tried so far:

class Fahrzeug
{
public:

    std::string Id() const;
    void Id(const std::string &id);

    friend std::ostream& operator<< (std::ostream &out, const Fahrzeug &fzg)
    {
        out << Id();
        return out;
    }

private:
    struct DatenImpl;
    boost::scoped_ptr<DatenImpl> _datenImpl;
};

This yields a compiler error:

error C2352: Id() - illegal call of non-static member function

How can I implement the ostream operator<< for a "pimpled" class?

Your definition should be:

friend std::ostream& operator<< (std::ostream &out, const Fahrzeug &fzg)
{
    out << fzg.Id();  // <--- qualify call to Id()
    return out;
}

The operator is not a class member, although defined inside the class .

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