C ++构造函数Oder [英] C++ Constructor Oder

查看:56
本文介绍了C ++构造函数Oder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

#include<iostream>
using namespace std;
class cls
{
public:
        cls(int i=0) {cout<<" c1 ";}
        ~cls() {cout<<" d 1 ";}
};
class cls2
{
 cls xx;
public:
        cls1(int i=0){cout<<" c2 ";}
        ~cls1(){cout<<" d2 ";}
}c;
class cls3
{
    cls2 xx; cls xxx;
public:
    cls2(int i=0) {cout<<" c3 ";}
    ~cls2(){ cout<<" d3 ";}
};
int main()
{
    cls3 s;
    return 0;
}

现在,当我运行它时,它输出:

Now, when I run it, it outputs:


c1 c2 c1 c2 c1 c3 d3 d1 d2 d1 d2 d1

c1 c2 c1 c2 c1 c3 d3 d1 d2 d1 d2 d1

我似乎无法弄清楚为什么在我的脑海中它应该输出:

and I can't seem to figure out why, in my head, it should output:


c1 c2 c1 c3 d3 d1 d2 d1

c1 c2 c1 c3 d3 d1 d2 d1

因为:

cls2 s -> cls1 xx -> cls xx => c1
                           => c2
                -> cls xxx => c1
                => c3

我知道在某个地方,我的逻辑有缺陷,但是我不知道在哪里。 p>

I know that somewhere, my logic is flawed, but I don't know where.

推荐答案

您要在此处创建一个额外的全局实例 c

You are creating an extra global instance c here:

class cls1
{
    int x; cls xx;
public:
        cls1(int i=0){cout<<" c2 ";x=i;}
        ~cls1(){cout<<" d2 ";}
} c; // <-- here

第一个被创建。

否则,您的预期订单就在现场。

Otherwise your expected order is spot-on.

这篇关于C ++构造函数Oder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆