为什么在重载operator <<!-时需要朋友关键字?

时间:2019-04-27 13:16:51

标签: c++ operator-overloading

在下面的示例中,我所有的成员都是公开的,所以我不明白为什么我仍然需要添加friend关键字。而且,此方法属于Point实例,因此我也不明白为什么我应该通过const Point% p引用我的属性。在+重载中,仅接收到外部实例。

#include <iostream>

struct Point {
    int x, y;
    Point(int x, int y): x(x), y(y) {};
    Point operator+(const Point& other) const {
        return Point(x + other.x, x + other.y);
    }

    friend std::ostream& operator<<(std::ostream& os, const Point& p) {
        return os << "(" << p.x << "," << p.y << ")";
    }
};

int main() {
    Point p = Point(4,7) + Point(8,3);
    std::cout << p << std::endl;
}

在这种情况下,类似one这样的类似问题并没有真正的帮助。

1 个答案:

答案 0 :(得分:3)

不,您不必在这里将流插入器变成朋友。问题在于代码在类定义内定义了插入器 。没有任何修饰,它将是一个普通的成员函数,而调用它将是语法上的噩梦。您可以将其设为kops update cluster --name ${KOPS_CLUSTER_NAME} --yes ssh admin@ec2-13-59-4-99.us-east-2.compute.amazonaws.com 成员,但这是违反直觉的。 static起作用的原因是副作用:将其标记为friend会将其定义推到类定义之外。因此,不必使用friend,只需在类定义之外进行定义即可。

friend