一个类在调用构造函数时,各个数据成员的构造顺序。

来源:互联网 发布:黄山烧饼哪家淘宝好吃 编辑:程序博客网 时间:2024/05/29 03:40

一个类在调用构造函数时,各个数据成员的构造顺序。

#include <iostream>class ShowIndex{public:    ShowIndex(int i) :i(i){ std::cout << "ctor " << this->i << std::endl; }    ~ShowIndex()          { std::cout << "dtor " << this->i << std::endl; }public:    int i;};class TheBase{public:    TheBase(char c) :_3(3), _1(1), _2(2){ std::cout << "ctor Base" << std::endl; }    ~TheBase()                          { std::cout << "dotr Base" << std::endl; }private:    ShowIndex _1;    ShowIndex _2;    ShowIndex _3;};class TheChild :public TheBase{public:    TheChild(char c) :_4(4), _5(5), _6(6), TheBase(c){ std::cout << "ctor Child" << std::endl; }    ~TheChild()                                      { std::cout << "dtor Child" << std::endl; }private:    ShowIndex _4;    ShowIndex _5;    ShowIndex _6;};class TheChild2 :public TheBase/*类似这样的写法会出现不可预知的行为*/{public:    TheChild2(char c) :_5(5), _4(_5.i - 1), TheBase(c){ std::cout << "ctor Child2" << std::endl; }    ~TheChild2()                                      { std::cout << "dtor Child2" << std::endl; }private:    ShowIndex _4;    ShowIndex _5;};int main(){    //一个类在调用构造函数的时候,不是按照你书写的"初始化列表"中的顺序进行构造的,    //是严格按照类里面的数据成员的先后/上下顺序进行构造的。    //当你继承了一个类时,你作为子类,必须先让父类构造完毕,才能轮到你。    //因为你作为一个对象,父类的数据成员在你这个子类的数据成员的前面。    if (true){        TheChild child('c');        std::cout << "======" << std::endl;    }    std::cout << std::endl;    //类似这样的,用未初始过的类的对象,给某对象初始化,会出现不可预知的行为。    //本例中的ShowIndex因为只有一个int数据成员,所以没有崩溃。    //如果ShowIndex换成一个比较复杂的类,比如boost::asio::io_service,那妥妥的就崩溃了。    if (true){        TheChild2 child('c');        std::cout << "======" << std::endl;    }    return 0;}
结果如下:

ctor 1ctor 2ctor 3ctor Basector 4ctor 5ctor 6ctor Child======dtor Childdtor 6dtor 5dtor 4dotr Basedtor 3dtor 2dtor 1ctor 1ctor 2ctor 3ctor Basector -858993461ctor 5ctor Child2======dtor Child2dtor 5dtor -858993461dotr Basedtor 3dtor 2dtor 1
完。

0 0
原创粉丝点击