14

我有两个班: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);

有什么办法吗?谢谢。

4

2 回答 2

14

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

class Point
{
public:
    friend Point Space::Point(int, int, int);
private:
    // ...
于 2013-07-12T21:56:00.640 回答
7

我会这样做:

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);
于 2013-07-12T23:03:51.043 回答