C++ Friend constructor

前端 未结 2 1837
自闭症患者
自闭症患者 2021-01-11 12:59

I have two classes : Point, that lives only in Space

class Point
{
private:
    Point(const Space &space, int x=0, int y=0, int         


        
2条回答
  •  无人及你
    2021-01-11 13:19

    I would do it like this:

    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);
    

提交回复
热议问题