2009-07-25 5 views
3

この小さなコードスニペットをC++で作成しましたが、出力も添付されています。 デストラクタに対して2つの呼び出しが行われているのに対し、コンストラクタが1回だけ呼び出される理由を理解できません。C++コンストラクタコール

私が理解から、デフォルトコンストラクタと、オーバーロード代入演算子はライン28

で呼び出されるべき誰かがこの上でいくつかの光を投げてくださいすることができ:

1 #include <iostream> 
    2 using namespace std; 
    3 
    4 class ABC { 
    5 char c; 
    6 public: 
    7  ABC() { 
    8  cout << "default" << endl; 
    9  } 
10  ABC(char c) { 
11  this->c = c; 
12  cout << c << endl; 
13  } 
14  ~ABC() { 
15  cout << hex << this << " destructor " << c << endl; 
16  } 
17  void method() { 
18  cout << "method" << endl; 
19  } 
20  void operator= (const ABC& a) { 
21  cout << "operator" << endl; 
22  } 
23 
24 }; 
25 
26 int main() { 
27 ABC b('b'); 
28 ABC a = b; 
29 } 

Output in g++ version 4.0.1: 
~/src$ g++ test.cpp 
~/src$ ./a.out 
b 
0xbffff0ee destructor b 
0xbffff0ef destructor b 
+0

コンストラクタタグの何が問題になっていますか? – GManNickG

答えて

11

あなただけの、コピーコンストラクタを呼び出している、これは定義されたコード:

ABC(const ABC& a):c(a.c){ 
    cout << "copying " << hex << &a << endl; 
} 

そして、あなたはこのような出力が表示shoud:デフォルトを呼び出したい場合は

b 
copying 0x7fffebc0e02f 
0x7fffebc0e02e destructor b 
0x7fffebc0e02f destructor b 

をコンストラクタと代入演算子を使用する場合は、別々の2つのステートメントを使用する必要があります。

ABC b('b'); 
    ABC a; 
    a = b; 
15
ABC a = b; 

acopy constructo r代入演算子ではありません!あなたが持っているもののようにそれを再定義することができ、コンパイラが生成したものです:あなたが本当にあなたのクラスに似converstion演算子を追加し、コピーコンストラクタを忘れることができますコピーコンストラクタを使用していないことを主張した場合

ABC(const ABC& other) 
{ 
c = other.c; 
cout << c << " copy constructor" << endl; 
} 

operator char() 
{ 
    return c; 
} 
+0

さらに、初期化リストを使用することもできます。 –

+0

さて、今のように、コピーコンストラクタには、コード –

+0

@litbに 'c 'の代入演算子の呼び出しが含まれています。これは本当ですか? – AraK

0

プログラムの出力は

parameterized constructor called 
b 
Copy cons 
0x7fff5fbff820 destructor � 
0x7fff5fbff828 destructor b 

であるあなたの

#include <iostream> 
using namespace std; 
class ABC { 
    char c; 
public: 

    ABC() { 
     cout << "default" << endl; 
    } 
     ABC(char c) 
     { 
      cout<<"parameterized constructor called\n";/////overloaded constructor called for the first line in main 
      this->c = c; 
      cout << c << endl; 
     } 
     ABC(ABC &c) 
     { 
      cout<<"Copy cons\n";//copy constructor is called for the second line in main 
     } 


     ~ABC() { 
      cout << hex << this << " destructor " << c << endl; 
     } 
     void method() { 
      cout << "method" << endl; 
     } 
     void operator= (const ABC& a) { 

     } 


    }; 


int main() 
{ 
     ABC b('b');//////here parameterized constructor is called i.e <ABC(char c)> 
     ABC a = b;/////////Here the copy constructor is called not the default one.(total 2 object created so the destructor is called twice!) 
} 

の変更されたコードを見てください今 コピーコンストラクタは、オブジェクト3例 1.Whenに呼び出された理由を説明することができますin initial 2.オブジェクトがパラメータとして関数に渡された場合 3.関数からオブジェクトが返された場合。

独自のコピーコンストラクタを指定しない場合、コンパイラはオブジェクトをビットごとにコピーする独自のコピーコンストラクタを実装します。コードから作成された2つのオブジェクトを追跡することができない独自のコピーコンストラクタを指定していません。 ありがとう

関連する問題