C++ Friend constructor

前端 未结 2 1816
自闭症患者
自闭症患者 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:17

    Yes, declare Space::Point() as a friend method. That method will receive access to Point's private members.

    class Point
    {
    public:
        friend Point Space::Point(int, int, int);
    private:
        // ...
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题