我有两个班级: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);
有没有办法这样做?感谢。
答案 0 :(得分:10)
是的,将Space::Point()
声明为朋友方法。该方法将获得Point
个私人成员的访问权限。
class Point
{
public:
friend Point Space::Point(int, int, int);
private:
// ...
答案 1 :(得分:6)
我会这样做:
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);