14

私は2つのクラスを持っています: 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 に答える