C++ Friend 语法/语义问题

标签 c++ stl

我的代码在以下时间被审查: 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?

是的。有一种方法。可以添加两个成员函数inputoutputpublic类(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/

相关文章:

java - JNA 内存泄漏

c++ - VS 启动程序时 WriteFile 行为不同

xcode - Cocoa App 中使用#include <string> 编译错误

c++ - 如何获得真实的硬件MAC地址

c++ - 用于网络的 Boost asio 库(http 客户端)

c++ - 创建 Linux GUI 元素我需要知道什么

C++ - 智能指针 vector 图 - 全部继承自同一基类

c++ - std::vector::front() 用于什么?

c++ - 如何将值从 vector 转换为 C++ 中的映射?

通过模板对unsigned int的C++限制