コンストラクターでの明示的初期化

C++クラス・オブジェクトは、コンストラクターを用いて明示的に初期化されるか、 またはデフォルト・コンストラクターを持っていなければなりません。 コンストラクターを使用する明示的初期化は、集合体初期化の場合を除き、 非静的定数および参照クラス・メンバーを初期化する唯一の方法です。

コンストラクター、仮想関数、private メンバーまたは protected メンバー、 および基底クラスのいずれも持たないクラス・オブジェクトは、集合体 と呼ばれます。 集合体の例としては、C 形式の構造体および共用体があります。

クラス・オブジェクトを作成する場合、そのオブジェクトを明示的に初期化します。 クラス・オブジェクトを初期化するには、次の 2 つの方法があります。

コンストラクターを用いてクラス・オブジェクトを明示的に初期化する 初期化指定子の構文を次に示します。

>>-+-(--expression--)-------------------+----------------------><
   '-=--+-expression------------------+-'
        |    .-,----------.           |
        |    V            |           |
        '-{----expression-+--+---+--}-'
                             '-,-'
 
 

次の例は、クラス・オブジェクトを明示的に初期化するいくつかの コンストラクターの宣言および使用の方法を示します。

// This example illustrates explicit initialization
// by constructor.
#include <iostream>
using namespace std;
 
class complx {
  double re, im;
public:
 
  // default constructor
  complx() : re(0), im(0) { }
 
  // copy constructor
  complx(const complx& c) { re = c.re; im = c.im; }
 
  // constructor with default trailing argument
  complx( double r, double i = 0.0) { re = r; im = i; }
 
  void display() {
    cout << "re = "<< re << " im = " << im << endl;
  }
};
 
int main() {
 
  // initialize with complx(double, double)
  complx one(1);
 
  // initialize with a copy of one
  // using complx::complx(const complx&)
  complx two = one;
 
  // construct complx(3,4)
  // directly into three
  complx three = complx(3,4);
 
  // initialize with default constructor
  complx four;
 
  // complx(double, double) and construct
  // directly into five
  complx five = 5;
 
  one.display();
  two.display();
  three.display();
  four.display();
  five.display();
}

上記の例で作成される出力は次のようになります。

re = 1 im = 0
re = 1 im = 0
re = 3 im = 4
re = 0 im = 0
re = 5 im = 0

関連参照

IBM Copyright 2003