【问题标题】:Is the constructor getting called here?构造函数是否在这里被调用?
【发布时间】:2011-03-21 18:27:06
【问题描述】:
#include<iostream>

class _ctor
{
public:
_ctor() { std::cout<<"\nCtor";}
~_ctor(){ std::cout<<"\nDtor";}
};

_ctor A(); // --> Is the Constructor Really called? I do not see the Output printed
//_ctor A;

int main(){
return 0;
}

上面代码的输出在这个Link中给出 我没有看到构造函数被调用,可能是什么问题?如果不应该调用它,那么_ctor A(); 是什么意思?

【问题讨论】:

  • 仅供参考,名称_ctor 是保留的,这会使您的程序格式错误(这与已经回答的问题无关)。更多详情this question

标签: c++ visual-c++ c++11


【解决方案1】:

您声明了一个名为 A() 的函数,它返回一个 _ctor,但您从未调用过该函数。你甚至从未定义过那个函数。

不,_ctor 的构造函数没有被调用。

【讨论】:

【解决方案2】:

不,因为您实际上是在声明一个不带参数并返回_ctor 的函数。这叫做"the most vexing parse." 你可能想要这个:

_ctor A;

【讨论】:

    【解决方案3】:

    您正在声明一个名为 A 的函数,该函数返回一个 ctor 类对象,因此不会调用构造函数。

    如果你想创建一个 ctor 类的全局对象,你可以这样做:

    _ctor A;
    

    调用构造函数。

    【讨论】:

      【解决方案4】:

      为了能够调用构造函数,程序需要实例化类_ctor

      _ctor A();
      

      上面的语句是函数A()的原型,它的返回类型是_ctor

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-27
        • 1970-01-01
        • 1970-01-01
        • 2016-07-12
        • 1970-01-01
        • 2015-11-04
        相关资源
        最近更新 更多