我想了解如何显式构造函数调用主要使用下面的代码工程。显式使用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;
}
功能测试正在被呼叫,其中构造依赖关系1()被用作一个函数调用,而不是依赖关系1 ::依赖关系1()和代码运行完全正常。
现在,如果我用类似的概念创造Dependency2的对象D1,这是行不通的。 似乎我在这里做错了错误的理解。
需要知道编译器如何解析依赖关系1()在主通话,即使不使用范围解析和它为什么当我使用它作为Dependency2
谢谢, 的构造函数的参数不工作阿南德
+1简单易懂,易于理解。 – 2010-12-24 05:28:13
谢谢,但是为什么当我使用类似的东西来创建Dependency2对象时它不起作用。 – Anand 2010-12-24 05:30:26
@Anand:看看我的答案。 – 2010-12-24 05:40:10