在为类配备“operator<<”时如何不使用友元声明

Ale*_*are 0 c++

我知道我们想做这样的事情来覆盖operator<<

#include <iostream>

class Point
{
private:
    double m_x{};
    double m_y{};
    double m_z{};

public:
    Point(double x=0.0, double y=0.0, double z=0.0)
      : m_x{x}, m_y{y}, m_z{z}
    {
    }

    friend std::ostream& operator<< (std::ostream& out, const Point& point);
};

std::ostream& operator<< (std::ostream& out, const Point& point)
{
    // Since operator<< is a friend of the Point class, we can access Point's members directly.
    out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ')'; // actual output done here

    return out; // return std::ostream so we can chain calls to operator<<
}

int main()
{
    const Point point1{2.0, 3.0, 4.0};

    std::cout << point1 << '\n';

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

来源:https ://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/

但是如果我不需要访问私有成员变量怎么办?我可以继续使用friend,但我不想这样做,因为我认为这会使代码变得混乱。但我不知道如何不使用friend. 我试过:

  1. 只是删除friend,但编译器会插入隐式this指针作为第一个参数,这不是我想要的。
  2. 更改friendstatic,但我的 IDE 抱怨operator<<不能是静态的。

pao*_*olo 5

您只需operator<<在相同的命名空间(在本例中为全局命名空间)中声明为自由函数Point,ADL 就会处理它:

#include <iostream>

class Point {
   private:
    double m_x{};
    double m_y{};
    double m_z{};

   public:
    Point(double x = 0.0, double y = 0.0, double z = 0.0)
        : m_x{x}, m_y{y}, m_z{z} {}

};

std::ostream& operator<<(std::ostream& out, const Point& point) {
    out << "Point";
    // Use public interface of point here.
    return out;
}

int main() {
    const Point point1{2.0, 3.0, 4.0};

    std::cout << point1 << '\n';

    return 0;
}
Run Code Online (Sandbox Code Playgroud)