Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator<< for printing as a member

Is there a way to overload the << operator, as a class member, to print values as a text stream. Such as:

class TestClass {
public:
    ostream& operator<<(ostream& os) {
        return os << "I'm in the class, msg=" << msg << endl;
    }

private:
    string msg;
};


int main(int argc, char** argv) {
    TestClass obj = TestClass();
    cout << obj;

    return 0;
}

The only way I could think of was to overload the operator outside of the class:

ostream& operator<<(ostream& os, TestClass& obj) {
    return os << "I'm outside of the class and can't access msg" << endl;
}

But then the only way to access the private parts of the object would be to friend the operator function, and I'd rather avoid friends if possible and thus ask you for alternative solutions.

Any comments or recommendations on how to proceed would be helpful :)

like image 552
ChewToy Avatar asked Dec 12 '11 14:12

ChewToy


People also ask

Can we overload << operator using the member function?

When overloading an operator using a member function: The overloaded operator must be added as a member function of the left operand. The left operand becomes the implicit *this object. All other operands become function parameters.

Can we overload << operator in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.

What is the advantage of overloading the << and >> operators?

By overloading the operators, we can give additional meaning to the operators like +-*/=.,= etc., which by default are supposed to work only on standard data types like int, float, char, void etc. It is an essential concept in C++.

Which function overloads the << operator in Python?

The operator overloading in Python means provide extended meaning beyond their predefined operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class and "str" class.


1 Answers

It needs to be a non-member, since the class forms the second argument of the operator, not the first. If the output can be done using only the public interface, then you're done. If it needs access to non-public members, then you'll have to declare it a friend; that's what friends are for.

class TestClass {
public:
    friend ostream& operator<<(ostream& os, TestClass const & tc) {
        return os << "I'm a friend of the class, msg=" << tc.msg << endl;
    }

private:
    string msg;
};
like image 167
Mike Seymour Avatar answered Oct 17 '22 06:10

Mike Seymour