Sep 5, 2012 at 5:48am UTC
Pls can I know how to overload the << operator?, to display all the displayable contents in a class?!?
Sep 5, 2012 at 6:05am UTC
Put a
friend
function in the class to allow your overloading function to access private members of the class. (If you only want to use public members, then don't worry about this step).
Then create a function external to the class that will handle this behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
class MyClass
{
int a;
int b;
public :
MyClass() : a(0), b(1) {}
friend std::ostream& operator << (std::ostream& o, MyClass c);
};
std::ostream& operator << (std::ostream& o, MyClass c)
{
o << c.a << ' ' << c.b;
return o;
}
int main()
{
MyClass A;
std::cout << A << std::endl;
}
0 1
Last edited on Sep 5, 2012 at 6:12am UTC
Sep 5, 2012 at 6:24am UTC
What does MyClass() : a(0), b(1) {}
mean?!?
Sep 5, 2012 at 6:42am UTC
It's the constructor. When you create an instance of MyClass
, a
is given the value 0 and b
is given the value 1.
Last edited on Sep 5, 2012 at 6:43am UTC
Sep 5, 2012 at 6:47am UTC
But why isn't it in the curly brackets{} ?
Sep 5, 2012 at 6:52am UTC
it's the shorter and better way to initialize.
int a = 0;
can be declared as
int a(0);
1 2 3 4 5 6
MyClass::MyClass()
{
//body
a = 0;
b = 1;
}
can be written as
1 2 3 4 5
MyClass::MyClass()
: a(0), b(1)
{
//body
}
this way both a and b are initialized before the constructor's body {} is called, so it is faster than assigning a and b in the body
Last edited on Sep 5, 2012 at 6:53am UTC