Original Post
Hi all,
I am trying to overload the stream input and output operators. I will keep things to the output operator for now (<<). Here's the question:
I can do this and everything is great--
#include <iostream>
class foo
{
public:
explicit foo() :
m_var(0.0f)
{}
virtual ~foo()
{}
friend std::ostream& operator << (std::ostream &os, const foo& myFoo)
{
os << "m_var = " << myFoo.m_var << std::endl;
return os;
}
private:
float m_var;
};
but I can't do this to the friend function--
static std::ostream& operator << (std::ostream &os, const foo& myFoo)
{
os << "m_var = " << myFoo.m_var << std::endl;
return os;
}
This is what I get--
error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class foo' (or there is no acceptable conversion)
Why not? When I have a static, the this ptr isn't passed, so things should be the same as if I had declared the function outside of the scope of the class, except I have access to the passed class members.
I have ST(Friendly?)W and found that everyone uses the friend variety of implementation. I am just wondering why a static implementation doesn't work.
Thanks in advance.
Jeeky
P.S. I can also do this--
std::ostream& operator << (std::ostream &os, const foo& myFoo)
{
os << "booger" << std::endl;
//os << "m_var = " << myFoo.m_var << std::endl;
return os;
}
This function was declared at the file scope (not within the class) and it works fine except for not having access to privates. Functionally, it should be identical to a static within the class. What gives?
[edited by - jeeky on October 28, 2002 11:40:59 PM]