Overloading operator << - C++

后端 未结 7 1803
Happy的楠姐
Happy的楠姐 2021-02-10 07:25

Background

I have a container class which uses vector internally. I have provided a method AddChar(std::string) to this wrap

7条回答
  •  萌比男神i
    2021-02-10 08:07

    The operator is not correctly overloaded here. There is no reason to make the operator a friend since it can be a member of the class. Friend is for functions which are not actual members of the class (such as when overloading << for ostream so the object can be output to cout or ofstreams).

    What you actually want the operator to be:

    ExtendedVector& operator<<(const std::string str){
        AddChar(str);
        return *this;
    }
    

    It is usually considered bad practice to overload operators in a way that has them do something than they do normally. << is normally bit shift, so overloading it this way can be confusing. Obviously STL overloads << for "stream insertion" and so along with that it might make sense to overload it for your use in a similar way. But that doesn't seem like what you're doing, so you probably want to avoid it.

    There are no performance issues since operator overloading is the same as a regular function call, just the call is hidden because it is done automatically by the compiler.

提交回复
热议问题