【发布时间】:2010-12-24 05:21:31
【问题描述】:
我正在尝试使用以下代码了解 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;
}
函数 test 被调用,其中构造函数 Dependency1() 用作函数调用而不是 Dependency1::Dependency1( ) 和代码运行良好。
现在如果我使用类似的概念来创建 Dependency2 的对象 D1,它就不起作用。 似乎我在这里做错了什么是基于错误的理解。
需要知道编译器如何在 main 中解析 Dependency1() 调用,即使没有使用范围解析,以及为什么当我将它用作 Dependency2 的构造函数中的参数时它不起作用
谢谢, 阿南德
【问题讨论】:
标签: c++ constructor temporary most-vexing-parse