2016-05-24 2 views
0

私は学生で、私はC++を学んでいます。私はC++をかなり上手く使っていますが、まだ "シンプル"なものが私を絡ませています。私はこのコードを持っているクラス、メソッド、コンストラクタ/デコンストラクタ、継承、仮想などを最近学びました:クラスのデストラクタを返す

#include <iostream> 
using namespace std; 

class test { 
    int a, c; 
public: 
    test() { cout << "Constructor\n"; } 
    test(int a) :a(a) { cout<<"Explicit Constructor\n"; } 
    test foo(const test&, const test&); 
    ~test() { cout << "DECONSTRUCTOR!\n"; } 
}; 

test test::foo(const test &t1, const test &t2) { 
    test rez; 
    rez.c = t1.a + t2.a; 
    return rez; 
} 

void main() { 
    test t1(5), t2(21), rez; 
    rez.foo(t1, t2); 
    cin.ignore(); 
} 

私がfooで、私はスコープのうちに削除されたローカルクラスを作成することを知っています。だからfooが呼び出されると、コンストラクタとデストラクタが1つずつ表示されるはずですが、それはもう1つのデコンストラクタを与えます。したがって、2つのデストラクタに対して1つのコンストラクタがあります。

+1

あなたにもコピーコンストラクタプリントを持っている必要があります。 – NathanOliver

+1

ただのFYI:コンストラクタは単一の 'int'引数を取っていますが、実際にはC++の用語を使った* explicit *ではありません。 –

+0

私は他の誰かが決定的な答えを出すようにするつもりですが、あなたが見ていることは 'test :: foo'内の' rez'が破壊されていること、そして 'rez.foo(t1 、t2) '破壊されている – Hill

答えて

2

の呼び出し元にrezオブジェクトをコピーするために使用されています:

test(test const &) { cout << "Copy constructor" << endl; } 

何が起こるか見てみましょう。

0

あなたはコピーコンストラクタを実装するために忘れてしまった:

test(const test &rhs) 
{ 
    cout << "Constructor"; 
} 

あなたのclass testへの1つの以上の方法追加のバックfoo

0

はコメントを参照してください:

test test::foo(const test &t1, const test &t2) { 
    test rez; 
    // constructor for rez invoked 
    rez.c = t1.a + t2.a; 
    return rez; 
    // destructor for rez invoked 
} 

void main() { 
    test t1(5), t2(21), rez; 
    // 3 constructor invocations 
    rez.foo(t1, t2); 
    // constructor for return value is called 
    // but you are missing it since you did not implement copy constructor 
    // destructor for return value is called 
    // as you did not use it 
    cin.ignore(); 
    // 3 destructor invocations 
}