My code was reviewed on:
https://codereview.stackexchange.com/questions/3754/c-script-could-i-get-feed-back/3755#3755
The following was used:
class Point
{
public:
float distance(Point const& rhs) const
{
float dx = x - rhs.x;
float dy = y - rhs.y;
return sqrt( dx * dx + dy * dy);
}
private:
float x;
float y;
friend std::istream& operator>>(std::istream& stream, Point& point)
{
return stream >> point.x >> point.y;
}
friend std::ostream& operator<<(std::ostream& stream, Point const& point)
{
return stream << point.x << " " << point.y << " ";
}
};
by another member. I don’t understand what friend functions are doing. Is there another way to do this without making them friend functions? And how can the client access them when they are private using the following? Could someone expound on what exactly is being returned?
int main()
{
std::ifstream data("Plop");
// Trying to find the closest point to this.
Point first;
data >> first;
// The next point is the closest until we find a better one
Point closest;
data >> closest;
float bestDistance = first.distance(closest);
Point next;
while(data >> next)
{
float nextDistance = first.distance(next);
if (nextDistance < bestDistance)
{
bestDistance = nextDistance;
closest = next;
}
}
std::cout << "First(" << first << ") Closest(" << closest << ")\n";
}
Yes. Since
friendfunctions are not member of the class, it doesn’t matter where you define them or declare them. Any can use them. The access rules don’t apply on them.operator>>()returnsstd::istream&which is reference to input stream.And
operator<<()returnsstd::ostream&which is reference to output stream.Yes. There is a way. You can add two member functions
inputandoutputto thepublicsection of the class, which will do whatfriendfunctions are doing now, and you can makeoperator<<andoperator>>non-friend functions as follows: