I overloaded the << operator of a class. How do I have to overload the operator if I want to use it on pointers, like the following?
class A {
std::string operator<<(std::string&);
}
aInst << "This works";
aPointer << "This doesnt work";
aPointer->operator<<("Whereas this works but is useless");
I hope you can help me.
heinrich
The class member access operator (->) can be overloaded but it is bit trickier. It is defined to give a class type a "pointer-like" behavior. The operator -> must be a member function. If used, its return type must be a pointer or an object of a class to which you can apply.
operators can be performed even when the pointers point to elements of different arrays. You can assign to a pointer the address of a data object, the value of another compatible pointer or the NULL pointer.
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.
Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof , which is technically an operator). C++ adds a few of its own operators, most of which can be overloaded except :: and .
You need to dereference the pointer first.
A *ptr = new A();
(*ptr) << "Something";
The only other way is the way you described above
Edit: Andre's solution below is workable as well, but like he said it may not be a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With