Overloading operator << - C++

后端 未结 7 1664
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条回答
  •  臣服心动
    2021-02-10 08:10

    I'd prefer not to overload it that way personally because vectors don't normally have an overloaded left shift operator - it's not really it's idiom ;-)

    I'd probably return a reference from AddChar instead like so:

    ExtendedVector& AddChar(const std::string& str) {
        container.push_back(str);
        return *this;
    }
    

    so you can then do

    container.AddChar("First").AddChar("Second");
    

    which isn't really much bigger than bitshift operators.

    (also see Logan's comment about passing strings in by reference instead of by value).

提交回复
热议问题