为什么重载运算符时需要友元关键字<<
Why is friend keyword required when overloading operator<<?
在下面的示例中,我的所有成员都是公开的,所以我不明白为什么我仍然需要添加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;
}
在这种情况下,像这样的类似问题并没有真正的帮助。
不,您不必让这里的流插入器成为朋友。问题是代码在类定义中定义了插入器。没有任何修饰,它将是一个普通的成员函数,调用它将是一个语法噩梦。你可以让它成为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++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 将子类方法声明为基类的友元
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- 友元方法作为常量
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 为什么重载运算符时需要友元关键字<<