我正在尝试使用以下代码了解 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 的构造函数中的参数时它不起作用
谢谢, 阿南德
最佳答案
test(Dependency1())
这调用函数 test
并传递类 Dependency1
的临时对象。因为 test
定义中的形式参数是对 const
的引用,并且因为临时对象可以绑定(bind)到 const
引用,所以您的代码可以正常工作。
Dependency2 D1(Dependency1()); // this line does not work
这被称为 C++ 最令人烦恼的解析。 D1
被解释为返回 Dependency2
的函数,并将参数作为指向返回 Dependency1
的函数的指针。
尝试 Dependency2 D1((Dependency1()));
并查看输出的变化。
注意:多加一对括号会使编译器将 (Dependency1())
视为表达式。
关于c++ - 显式使用 main 中的构造函数调用作为函数调用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4524394/