C++Friend构造函数

C++ Friend constructor

本文关键字:构造函数 C++Friend      更新时间:2023-10-16

我有两个类:Point,它只存在于Space

class Point
{
private:
    Point(const Space &space, int x=0, int y=0, int z=0);
    int x, y, z;
    const Space & m_space;
};

构造函数是故意私有的,我不想直接调用它。我想用这种方式创建点

Space mySpace;
Point myPoint = mySpace.Point(5,7,3);

有什么办法吗?谢谢

是,将Space::Point()声明为友元方法。该方法将接收对Point的私有成员的访问权限。

class Point
{
public:
    friend Point Space::Point(int, int, int);
private:
    // ...

我会这样做:

class Space
{
public:
    class Point
    {
    private:
        Point(const Space &space, int x=0, int y=0, int z=0);
        int m_x, m_y, m_z;
        const Space & m_space;
    friend class Space;
    };
    Point MakePoint(int x=0, int y=0, int z=0);
};

Space::Point::Point(const Space &space, int x, int y, int z)
    : m_space(space), m_x(x), m_y(y), m_z(z)
{
}
Space::Point Space::MakePoint(int x, int y, int z)
{
    return Point(*this, x, y, z);
}

Space mySpace;
Space::Point myPoint = mySpace.MakePoint(5,7,3);