【问题标题】:explicitly using constructor call in main as a function call parameter在 main 中显式使用构造函数调用作为函数调用参数
【发布时间】: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


    【解决方案1】:

    test(Dependency1())

    这会调用一个函数test 并传递一个类Dependency1 的临时对象。因为test 定义中的形式参数是对const 的引用,并且因为临时对象可以绑定到const,所以引用您的代码有效。

    Dependency2 D1(Dependency1()); // this line does not work

    这被称为 C++ 最令人头疼的解析。 D1 被解释为返回 Dependency2 的函数,并接受一个指向返回 Dependency1 的函数的指针。

    试试Dependency2 D1((Dependency1())); 看看输出的变化。

    注意:添加一对额外的括号会使编译器将(Dependency1()) 视为表达式。

    【讨论】:

    • 太好了。谢谢。有没有其他方法可以让编译器将 D1 识别为对象而不是函数?
    • 所以如果我的理解是 write ,编译器将 Dependency2 D1 (Dependency1()) 视为函数声明,这就是该行没有执行的原因。
    • @Anand :我已经提出了一个方法。再次阅读帖子。
    • @Prasoon:你身边的完美答案。
    【解决方案2】:

    Dependency1() 创建一个类型为 Dependency1 的临时对象,将其传递给函数测试。

    【讨论】:

    • 谢谢,但是为什么当我使用类似的东西来创建 Dependency2 对象时它不起作用。
    • @Anand:看看我的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2016-02-29
    • 2021-11-23
    • 2010-09-12
    相关资源
    最近更新 更多