次のコードを使用して、メインでの明示的なコンストラクター呼び出しがどのように機能するかを理解しようとしています。
#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のコンストラクターでパラメーターとして使用すると機能しない理由を知る必要があります
ありがとう、アナンド