Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using overloaded operators on pointers

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

like image 935
Erik Avatar asked Oct 29 '10 19:10

Erik


People also ask

Can pointer operator be overloaded?

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.

Can you use operators on pointers?

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.

Does C Sharp support operator overloading?

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.

Can we overload arrow operator in C++?

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 .


1 Answers

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.

like image 123
Mike Bailey Avatar answered Oct 17 '22 15:10

Mike Bailey