2013-07-12 17 views
8

私は2つのクラスがあります:Point、唯一SpaceC++友達のコンストラクタ

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

がそうするどのような方法がありますポイントを作成したいのですが?ありがとう。

+1

研究[ 'friend'](http://en.cppreference.com/w/cpp/language/friend)のクラスと関数。 –

+0

*コンストラクタは意図的にプライベートです* ...なぜですか? –

答えて

10

はい、Space::Point()を友人として宣言してください。このメソッドにはPointのプライベートメンバーへのアクセス権が与えられます。

class Point 
{ 
public: 
    friend Point Space::Point(int, int, int); 
private: 
    // ... 
+0

ありがとうございますが、コンストラクタと同じ名前を使用するのは好きではありません: 'Point Space :: Point(int、int、int)の宣言は' Point 'の意味を' struct Point 'から変更します。私はちょうどそれを名前を変更する必要がありますね。 – Heretron

+0

@ user2578002 Pointオブジェクトを作成するときに 'your :: namespace :: Point(x、y、z)'のように完全修飾名を使うこともできます。 – cdhowie

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

代わりにありがとう、問題は、私は常にポイントを操作するためにスペースクラスを参照する必要があります mySpace.p1 + mySpace.p2、私は心に入れ子クラスを維持します – Heretron

関連する問題