c++ - 为什么重载operator<<时需要friend关键字?

标签 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在这种情况下并没有真正的帮助。

最佳答案

不,您不必将此处的流插入器设为 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/

相关文章:

c++ - MS CryptoAPI 在带有 CryptAcquireContext() 的 Windows XP 上不起作用

c++ - 解决 operator[] 的不明确重载

c++ - 如何从头文件将运算符定义添加到现有结构?

c++ - 检查字符串是否以 (%i) 结尾,然后将该数字分配给变量

python - 在 C++ 中运行 python

c++ - 包含对象指针的 STL 堆

C++ 认为 '<<' 不是类的成员,但它是

c++ - 在运算符重载参数列表中包含 const 会产生错误 (C++)

C++ 重载运算符 +()

c++ - 给出 if 条件的逻辑困惑