mainでの明示的なコンストラクタ呼び出しが次のコードを使用してどのように動作するかを理解しようとしています。コンストラクタDependency1()は代わりDependency1 :: Dependency1()の関数呼び出しとして使用され、コードが完全に正常に動作する場合mainで明示的にコンストラクタ呼び出しを関数呼び出しパラメータとして使用
#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;
}
機能試験が呼び出されています。
私は同様の概念を使用してDependency2のオブジェクトD1を作成すると機能しません。 私は間違った理解に基づいてここで何か間違っているようです。
コンパイラは、スコープ解決が使用されていないと私はDependency2のコンストラクタにパラメータとしてそれを使用する場合、なぜそれが
おかげで、 に動作しない場合であっても、メインでDependency1()の呼び出しを解決する方法を知っておく必要がありAnand
+1簡潔でわかりやすい。 –
ありがとう、しかし、私はDependency2オブジェクトを作成するために同様のことを使用すると、なぜ動作しません。 – Anand
@Anand:私の答えをチェックしてください。 –