What is the << operator for in C++?

后端 未结 6 1342
抹茶落季
抹茶落季 2021-01-21 13:21

I come from a C# and Java background into C++ and I\'m trying to get to understand the >> & << operators such as in

std         


        
6条回答
  •  感动是毒
    2021-01-21 14:14

    In the case of I/O streams the << and >> operators are overloaded to mean something other than bit shifting. For example, std::ostream::operator<< is overloaded for many types, and you can add overloads for your own types as well. For example:

    #include 
    #include 
    
    class my_type {
    public:
        my_type(const std::string &name) : _name(name) { }
        const std::string &get_name() const { return _name; }
    private:
        std::string _name;
    };
    
    std::ostream& operator<< (std::ostream& out, const my_type &foo ) {
        return out << foo.get_name();
    }
    
    int main() {
        my_type m("foo");
        std::cout << m;   // prints "foo"
        return 0;
    }
    

提交回复
热议问题