2016-04-14 9 views
-1

OtherThingクラスには、以下のメンバー変数theOtherThingを初期化する際に、 "Line"型のオブジェクトを受け取るコンストラクタがありますが、SomeClassのコンストラクタを通じてargLineを渡していません。コンストラクタで新しいLineオブジェクトを宣言したいのですが、どうしたらよいか分かりません。私はコンストラクタの本体で初期化することができたと思うし、多分私はあまりにも滑らかにしようとしている。C++メンバー初期化でコンストラクタ内に新しいオブジェクトを渡します

SomeClass::SomeClass(const Polygon& argPoly, 
        const Point& argPoint) 
        //No argLine being passed here 
    : 
     thePolygon   (argPoly), 
     thePoint    (argPoint), 
     theOtherThing  (new OtherThing(Line())), //Something like this 
          //But, the above does not work 
          //Nor (new OtherThing(Line aLine)) 
          //Nor (new OtherThing(new Line())   
{} 

OtherThingクラスは型のオブジェクトを取るコンストラクタを持っている「ライン」

OtherThing::OtherThing(const Line& argLine) 
    : 
     theLine    (argLine) 
{} 

ラインは、そのデータメンバを初期化するデフォルトコンストラクタを持っています。

Line::Line() 
{ 
    //Data members get initilized here 
} 

どうすればよいですか?多分、私はそれを複雑にしています。

EDIT theOtherThingの

宣言:

Private : 
    OtherThingPtr theOtherThing //It's an implementaion of C++ std::shrd_ptr 

EDIT

ラインクラス

class Line 
{ 
public: 
    double this; 
    double that; 
    Line(); 
    ... some other constructors and methods 
} 

OtherThingクラス

class OtherThing : RefCountedObj 
{ 
public: 
    OtherThing(const Line& argLine) 

private: 
    Line theLine; 
    ... 
} 
+0

ハハ。ちょうど冗談...新しいOtherThing(Line())が動作します。誰でも教育的な理由で精巧に扱っていますか? – KyleEnglish

+1

'theOtherThing'が' OtherThing'ならば、 'theOtherThing(Line {})'のみが必要です。 – NathanOliver

+0

'' OtherThing'( '' Line()) ''は、ポインタで作業していないので動作しません。実際にはうまくいったとは言えません... – KyleEnglish

答えて

1

Line()のバリアントがコンパイルされます。 OtherThingコンストラクタは左辺値の参照を受け取り、rvalue(一時オブジェクト)を渡します。この一時的なLineオブジェクトをOtherThingコンストラクタに使用することができます。問題はtheLineのタイプです。

theLineconst Line&の場合、オブジェクトの作成後にtheLineを参照すると、未定義の動作が呼び出されます。 theLineがちょうどLineの場合は、コピーコンストラクタを呼び出します。これはOKであるはずです。あなたが唯一の次の操作を行う必要があり

class OtherThing 
{ 
    OtherThing(const Line& argLine) : theLine(argLine){} 
    Line theLine; 
}; 

ポリゴン& thePoint状の部材、および(上記のように)以下のもの OtherThingためのコードであることクラス OtherThingに基づいて
+0

@NathanOliver私は[this](http://en.cppreference.com/w/cpp/language/reference_initialization#Lifetime_of_a_temporary)をもう一度読みました。私は何を意味するかを明確にするためにいくつかの変更を加える。それは私の答えと矛盾しますか? –

+0

Nathanは、問題がコンストラクタが参照を取っていることを示す最初の段落を参照している可能性があります。実際には、コンストラクタは正常です。 'OtherThing :: theLine'が実際に参照の場合、* that *はコンストラクター自体ではなく問題(またはコンストラクターへの呼び出し)です。 – user2079303

+0

@ user2079303はい、私は再調整すべきです。 –

0

SomeClass::SomeClass(const Polygon& argPoly, 
       const Point& argPoint) 
       //No argLine being passed here 
    : 
     thePolygon   (argPoly), 
     thePoint    (argPoint), 
     theOtherThing  (Line()), ... 
関連する問題