C ++如何覆盖类中的<<操作符

How would i override the << operator within a class? Or be able to print a vector<byte> from within a class. My current code looks like

ostream& operator<<(ostream& os, const vector<byte>& bytes)
{
    if (bytes.size() == 0)
        return os;

    for (size_t i = 0; i < bytes.size()-1; i++)
        os << hex << (int)bytes[i] << " ";
    os << bytes.back();
    return os;
}

It’s hanging outside of the class, and only functions outside of the class can cout << and print a vector<byte>. I want to be able to print one from within the class.

评论