Overloading the Insertion Operator

K

kvnsmnsn

I've been asked to overload the insertion operator. What exactly is
the insertion operator in C++, and how would one overload it? I think
that in C I could overload the "+" operator like so:

double operator+ ( char* left
, char* right)
{
// some code here
}

Could I do that in C++ too? Or is there a different way to do it?

---Kevin Simonson

"You'll never get to heaven, or even to LA,
if you don't believe there's a way."
from _Why Not_
 
A

Alf P. Steinbach

* (e-mail address removed):
I've been asked to overload the insertion operator. What exactly is
the insertion operator in C++

There is no insertion operator in C++, but, stretching the English
language, "<<" is used as an insertion operator for streams, and some
authors call that the C++ "insertion operator".

, and how would one overload it? I think
that in C I could overload the "+" operator like so:

double operator+ ( char* left
, char* right)
{
// some code here
}

As far as I know even C99 doesn't support operator overloading.

In C++ you can't overload on pointer types.

Could I do that in C++ too? Or is there a different way to do it?

A typical overload of "<<" goes like

struct MyClass
{
std::eek:stream& writeSelfOn( std::eek:stream& s ) const
{
return (s << "A myclass instance");
}
};

std::eek:stream& operator<<( std::eek:stream& s, MyClass const& x )
{
return x.writeSelfOn( s );
}

For the header file defining MyClass you need only include <iosfwd> if
you don't define writeSelfOn inline (above example is inline def).
 
J

jacob navia

Alf said:
* (e-mail address removed):

There is no insertion operator in C++, but, stretching the English
language, "<<" is used as an insertion operator for streams, and some
authors call that the C++ "insertion operator".



As far as I know even C99 doesn't support operator overloading.

lcc-win32, a C compiler, supports operator overloading as an extension.
 
?

=?ISO-8859-1?Q?Erik_Wikstr=F6m?=

* (e-mail address removed):

There is no insertion operator in C++, but, stretching the English
language, "<<" is used as an insertion operator for streams, and some
authors call that the C++ "insertion operator".



As far as I know even C99 doesn't support operator overloading.

In C++ you can't overload on pointer types.

To clarify, at least one of the operands of the operator has to be a
user defined type, i.e. you cannot change or add the operators of
built-in types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,157
Latest member
MercedesE4
Top