What's the right way to overload the stream operators << >> for my class?

后端 未结 4 1662
礼貌的吻别
礼貌的吻别 2020-12-19 09:49

I\'m a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What\'s the no

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 10:44

    There are several approaches and the right one really depends on what the class does.

    Quite often it makes sense to have public API that allows reading the information, in which case the streaming operators do not need to access privates.

    Probably the most popular approach is declaring the streaming functions friends of the class.

    My favorite is providing a public Boost.Serialization style template function that can be used for streaming either way, as well as for other things.

提交回复
热议问题