【问题标题】:C++ program starts execution from main and ends at main? [duplicate]C ++程序从main开始执行并在main结束? [复制]
【发布时间】:2019-02-20 19:40:41
【问题描述】:
#include <bits/stdc++.h>
using namespace std;

class A
{

public:
A()
   {
    cout<<"A is called";

    }
}a;

int main()

{
    cout<<"main is called";

}

但是这里先调用 A 函数,然后再调用 main 其背后的机制是什么?

【问题讨论】:

  • 了解静态存储时长,a是全局变量,所以在进入main函数之前创建。
  • #include &lt;bits/stdc++.h&gt; 不应使用 (why) 和 using namespace std;应避免使用 (why)。它们共同强化了对方的一些最糟糕的行为,导致一些非常难以理解的错误。不要这样做。

标签: c++ oop


【解决方案1】:

发生的事情是首先创建了A 类型的全局变量a。在构造函数中,您输出文本A is called,然后程序从主函数开始。

因此,您所看到的是意料之中的,并且您从中得出,在执行 main() 之前必须创建全局变量。

如果您查找static storage duration,您可以找到更多信息,全局对象有哪些。

注意:标准中未指定具有静态存储持续时间的对象的创建顺序,因此可以遵守任何顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2013-05-05
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2013-08-07
    • 2014-02-25
    相关资源
    最近更新 更多