C++委託構築関数

2422 ワード

c++11には,委任構造関数という新しい特性がある.委任コンストラクション関数は、現在のクラスの他のコンストラクション関数を使用して、現在のコンストラクション関数の初期化を支援します.すなわち、現在のコンストラクション関数の一部(またはすべて)の職責を本クラスの別のコンストラクション関数に渡すことができる.
まず,委任構造関数と通常の構造関数の同じ点と異なる点を見てみる.
   :
                       
   :
                           ,      (            )    

依頼されたコンストラクション関数の関数体にコードがある場合は、まず関数体のコードを実行してから、依頼コンストラクション関数に戻ります.ここでは、関数呼び出しとして理解できます(もちろん、両者には違いがあります).サンプルコードを見てみましょう
#include 
#include 
class A{
private:
    int _a;
    std::string _s;
public:
    //       
    A(std::string s, int a) : _a(a), _s(s){
        std::cout << "             " << std::endl;
    }
    //       
    A(int a): A("  A(int a)", a){
        std::cout << "         A(int a)    " << std::endl;
    }
    A(std::string s): A(s, 100){
        std::cout << "         A(std::string s)    " << std::endl;
    }
    A(): A("  A()", 4) { }
    A(std::ostream &out): A(){
        out << "       
"; } // void display() const{ std::cout << "---------------------" << std::endl; std::cout << "s = " << _s << std::endl; std::cout << "a = " << _a << std::endl; std::cout << "---------------------" << std::endl; } }; int main() { A a(" A(std::string s, int a)", 1); a.display(); A b(2); b.display(); A c(" A(std::string s)"); c.display();      A d(std::cout); d.display(); return 0; }

このコードにより,構造関数を依頼する役割が容易に理解できる.次にいくつかの間違った例を見てみましょう.
Case 1:メンバー初期化リスト
class B{
    int _a;
    std::string _s;
    B(int a): _a(a){ }
    B(std::string s): _s(s){ }
    //     
    //                ,         
    //           
    //   1:                    
    B(int a, std::string s): _a(a), B(s){ }
    B(int a, std::string s): B(a), _s(s){ }
    //   2:                
    B(int a, std::string s): B(a), B(s){ }
};

Case 2:ループコール
class B{
private:
    int _a;
    std::string _s;
public:
    B(int a): B("Test") {
        _a = a;
    }
    B(std::string s): B(100){
        _s = "          !!!";
    }
};
このコードはコンパイルできますが、実行できません.初期化すると、どの関数を実行しても無限のループ呼び出しに陥るからです.