'friend' functions and << operator overloading: What is the proper way to overload an operator for a class?

前端 未结 3 1069
眼角桃花
眼角桃花 2020-11-28 03:25

In a project I\'m working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation

3条回答
  •  有刺的猬
    2020-11-28 04:06

    Let's say you wanted to write an operator overload for + so you could add two Score objects to each other, and another so you could add an int to a Score, and a third so you could add a Score to an int. The ones where a Score is the first parameter can be member functions of Score. But the one where an int is the first parameter can't become member functions of int, right? To help you with that, you're allowed to write them as free functions. That is what is happening with this << operator, you can't add a member function to ostream so you write a free function. That's what it means when you take away the Score:: part.

    Now why does it have to be a friend? It doesn't. You're only calling public methods (getPoints and scoreGetName). You see lots of friend operators because they like to talk directly to the private variables. It's ok by me to do that, because they are written and maintained by the person maintaing the class. Just don't get the friend part muddled up with the member-function-vs-free-function part.

提交回复
热议问题