C++ Constructor Oder [closed]

 ̄綄美尐妖づ 提交于 2019-12-14 03:34:44

问题


Consider the following piece of code:

#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

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

c1 c2 c1 c3 d3 d1 d2 d1

because:

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

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


回答1:


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

That one is created first.

Otherwise your expected order is spot-on.



来源:https://stackoverflow.com/questions/39229494/c-constructor-oder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!