我的代码在以下时间被审查: https://codereview.stackexchange.com/questions/3754/c-script-could-i-get-feed-back/3755#3755
使用了以下内容:
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 << " ";
}
};
由另一个成员。我不明白 friend 功能在做什么。有没有另一种方法可以在不使它们成为 friend 功能的情况下做到这一点?当他们使用以下内容私有(private)时,客户端如何访问它们?有人可以解释一下究竟返回了什么吗?
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";
}
最佳答案
And how can the client access them when they are private using the following?
是的。自 friend
函数不是类的成员,在何处定义或声明它们并不重要。任何人都可以使用它们。访问规则不适用于它们。
Could someone expound on what exactly is being returned?
operator>>()
返回 std::istream&
这是对输入流的引用。
和 operator<<()
返回 std::ostream&
这是对输出流的引用。
Is there another way to do this without making them friend functions?
是的。有一种方法。可以添加两个成员函数input
和 output
到 public
类(class)的一部分,将做什么friend
功能正在做,你可以做operator<<
和 operator>>
非好友函数如下:
class Point
{
public:
//....
std::istream& input(std::istream& stream)
{
return stream >> point.x >> point.y;
}
std::ostream& output(std::ostream& stream) const
{
return stream << point.x << " " << point.y << " ";
}
//...
};
std::istream& operator>>(std::istream& stream, Point& point)
{
return point.input(stream);
}
std::ostream& operator<<(std::ostream& stream, Point const& point)
{
return point.output(stream);
}
关于C++ Friend 语法/语义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6887981/