Re: Question on operator << overloading
* shuisheng:
I have a question on operator << overloading on a class in a
namespace. For example:
#include <iostream>
namespace Geometry
{
class Point
{
friend std::ostream& operator << (std::ostream& out, const Point&
pt);
private:
double x, y, z;
};
};
inline std::ostream& operator << (std::ostream& out, const Point& pt)
{
out << pt.x << pt.y << pt.z;
return out
}
I got compilation errors: can not access class Point 's private
members x, y, and z. If I move the overloading function into the
Geometry namespace, it is fine. But I want to keep the function
global and do not want to make x, y, z public, how can I do for it?
<code file="A.cpp">
#include <iostream>
namespace Geometry {
class Point;
}
inline std::ostream& operator<<(
std::ostream& out,
Geometry::Point const& pt
);
namespace Geometry {
class Point
{
friend std::ostream& ::operator<<(
std::ostream& out,
Geometry::Point const& pt
);
private:
double x, y, z;
};
}
inline std::ostream& operator<<(
std::ostream& out,
Geometry::Point const& pt
)
{
return out << pt.x << " " << pt.y << " " << pt.z;
}
</code>
<code file="B.cpp">
#include <iostream>
namespace Geometry {
class Point
{
public:
std::ostream& writeOn( std::ostream& out ) const
{
return out << x << " " << y << " " << z;
}
private:
double x, y, z;
};
}
inline std::ostream& operator<<(
std::ostream& out,
Geometry::Point const& pt
)
{
return pt.writeOn( out );
}
</code>
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!