-
Defining operators
I recently learned how to declare types ex. time_t
like
typedef long double n_type;
How do you create operators?
in iostream the redefined << and >> for cout and cin (god know's why?)
how do I make new operators.
oh and also I am looking for a website on understanding header files because my friend is also learning and I can't explain it RIGHT. So I am looking for material in that are too.
Any help would be appreciated.
-
-
>(god know's why?)
Why? What if you have a class that you would like to print directly with cout?
Code:
#include <iostream>
class Test
{
int i, j;
public:
Test ( int one, int two ) :
i ( one ), j ( two )
{}
};
int main()
{
Test t ( 10, 20 );
std::cout<< t <<std::endl;
return 0;
}
This will obviously not work because cout isn't defined for objects of class Test. You need to define it yourself:
Code:
#include <iostream>
class Test
{
int i, j;
public:
Test ( int one, int two ) :
i ( one ), j ( two )
{}
friend std::ostream& operator<< ( std::ostream& os, const Test& t )
{
os<< t.i <<" -- "<< t.j;
return os;
}
};
int main()
{
Test t ( 10, 20 );
std::cout<< t <<std::endl;
return 0;
}
Now everything works just peachy.
-Prelude
-
I think L-P was questioning the use of the shift left and shift right operators as insertion operators. That's a reasonable concern but not something that matters a whole lot. I will frequently overload the [] operators but others are more rare.