2

次のコードを使用して、メインでの明示的なコンストラクター呼び出しがどのように機能するかを理解しようとしています。

#include<iostream>

using namespace std;

class Dependency1
{
      bool init;
public:
  Dependency1() : init(true) {
    std::cout << "Dependency1 construction"
              << std::endl;
  }
  void print() const {
    std::cout << "Dependency1 init: "
              << init << std::endl;
  }



};


class Dependency2 {
   Dependency1 d1;
public:
   Dependency2(const Dependency1& dep1): d1(dep1){
     std::cout << "Dependency2 construction ";
     print();
   }
   void print() const { d1.print(); }
};

void test( const Dependency1& dd1)
{
    cout  << " inside Test \n";
    dd1.print();
}



int main()
{

    test(Dependency1());
    Dependency2 D1(Dependency1()); // this line does not work

    return 0;
}

関数テストは、コンストラクターDependency1()がDependency1::Dependency1( )の代わりに関数呼び出しとして使用されている場所で呼び出されており、コードは完全に正常に実行されます。

同様の概念を使用して Dependency2 のオブジェクト D1 を作成すると、機能しません。間違った理解に基づいて、ここで何か間違ったことをしているようです。

スコープ解決が使用されていない場合でも、コンパイラがメインで Dependency1() 呼び出しを解決する方法と、それをDependency2のコンストラクターでパラメーターとして使用すると機能しない理由を知る必要があります

ありがとう、アナンド

4

2 に答える 2

7

test(Dependency1())

これは関数testを呼び出し、 class の一時オブジェクトを渡しますDependency1。の定義の正式なパラメーターはtestへの参照でconstあり、一時変数を参照にバインドできるためconst、コードは機能します。

Dependency2 D1(Dependency1()); // this line does not work

これは、C++ の最も厄介な解析と呼ばれます。D1を返す関数として解釈され、 を返すDependency2関数へのポインタを引数に取りますDependency1

Dependency2 D1((Dependency1()));出力の変化を試してみてください。

注: 余分な括弧のペアを入れると、コンパイラ(Dependency1())は式として扱われます。

于 2010-12-24T05:30:47.787 に答える
1

Dependency1() は、関数 test に渡されるタイプ Dependency1 の一時オブジェクトを作成します。

于 2010-12-24T05:24:46.343 に答える