在下面的示例中,我的所有成员都是公开的,所以我不明白为什么我还需要添加 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在这种情况下并没有真正的帮助。
最佳答案
不,您不必将此处的流插入器设为 friend 。问题在于代码在类定义中 定义了插入器。如果没有任何装饰,它将是一个普通的成员函数,调用它将会是一场语法噩梦。您可以将其设为 static
成员,但这是违反直觉的。 friend
使它起作用的原因是一个副作用:将其标记为 friend
会将其定义推到类定义之外。因此,不要使用 friend
,只需在类定义之外定义它即可。
#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);
}
};
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;
}
关于c++ - 为什么重载operator<<时需要friend关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55880947/