Reputation: 126
Here is the sample code:
#include <iostream>
using namespace std;
class test
{
int a;
int b;
public:
test(): a(1), b(2) {}
ostream& operator<<(ostream&); //FUNC 1
friend ostream& operator<<(ostream&,test); //FUNC 2
};
//FUNC 1
ostream& test::operator<<(ostream& obj)
{
cout<<a<<" "<<b<<endl;
return obj;
}
//FUNC 2
ostream& operator<<(ostream& obj, test o)
{
cout<<o.a<<" "<<o.b<<endl;
return obj;
}
int main()
{
test o;
o<<cout; //STATEMENT 1 Calls FUNC 1
cout<<o; //STATEMENT 2 Calls FUNC 2
return 0;
}
Is there any way to use STATEMENT 2 inside the class, i.e without making a friend function and passing the test object as a parameter. Using a definition like FUNC 1 for it?
Upvotes: 0
Views: 77
Reputation: 409176
When you make the "output" (actually shift left) operator a member of a class, it's for making an object of the class the target of the "output".
Simple example
struct Foo
{
Foo& operator<<(int value)
{
std::cout << "Output to Foo target is " << value << '\n';
return *this;
}
};
int main()
{
Foo foo;
foo << 123;
}
To use the output operator to output to another target (e.g. an output stream) you need to declare the operator as a non-member function:
struct Bar
{
int value;
};
std::ostream& operator<<(std::ostream& os, const Bar& bar)
{
os << bar.value;
}
int main()
{
Bar bar = { 321 };
std::cout << bar;
}
In the first example, the object (foo
) was the target of the output operator. In the second example, the object (bar
) is used as output to another target (std::cout
). You can also see it like this, if you overload an operator as a member function then the object of the class (the "target" as I call it) is on the left side of the operator and the argument is on the right side of the operator.
Also, if you declare a function inside the class using friend
then it's actually not a member function:
struct Fum
{
void ho() { ... } // ho is a member function
friend ha() { ... } // ha is a non-member function
};
And remember that operator functions are just normal functions, just with special names.
Upvotes: 2
Reputation: 5949
Your definition of function 2 ostream& test::operator<<(ostream& obj, test o)
is as a member function of the test
class. You want this to be a friend function external to the class: ostream& operator<<(ostream& obj, test o)
.
Upvotes: 2