6

私はこのクラスを持っています

class XXX {
    public:
        XXX(struct yyy);
        XXX(std::string);
    private:
        struct xxx data;
};

最初のコンストラクター(構造体を操作する)は簡単に実装できます。2つ目は、特定の形式で1つの文字列を分割し、解析して、同じ構造を抽出することができます。

私の質問は、Javaでは次のようなことができるということです。

XXX::XXX(std::string str) {

   struct yyy data;
   // do stuff with string and extract data
   this(data);
}

this(params)別のコンストラクターを呼び出すために使用します。この場合、私は似たようなことをすることができますか?

ありがとう

4

2 に答える 2

9

あなたが探している用語は、「コンストラクター委任」(または、より一般的には「連鎖コンストラクター」) です。C++11 より前は、これらは C++ には存在しませんでした。ただし、構文は基本クラスのコンストラクターを呼び出すのと同じです。

class Foo {
public:
    Foo(int x) : Foo() {
        /* Specific construction goes here */
    }
    Foo(string x) : Foo() {
        /* Specific construction goes here */
    }
private:
    Foo() { /* Common construction goes here */ }
};

C++11 を使用していない場合、できる最善の方法は、すべてのコンストラクターに共通のものを処理するプライベート ヘルパー関数を定義することです (ただし、これは初期化リストに入れたいものにとっては面倒です)。 . 例えば:

class Foo {
public:
    Foo(int x) {
        /* Specific construction goes here */
        ctor_helper();
    }
    Foo(string x) {
        /* Specific construction goes here */
        ctor_helper();
    }
private:
    void ctor_helper() { /* Common "construction" goes here */ }
};
于 2013-01-06T16:09:13.670 に答える
2

はい。C++11 では、それが可能です。これはコンストラクタ委任と呼ばれます。

struct A
{
   A(int a) { /* code */ }

   A() : A(100)  //delegate to the other constructor
   {
   }
};
于 2013-01-06T16:09:07.147 に答える