将Object初始化为另一个类的成员

时间:2015-09-19 05:41:39

标签: c++

我只是想了解它是如何发生的,因为它是c ++的新手。

让我详细说明我的问题陈述。

class test1 {
public:
    test1() {
        cout << " test1::constructor called" << endl;
    }
    ~test1() {
        cout << " test1::destrcutor called" << endl;
    }
};

class test2 {
public:
    test2() {
        cout << " test2::constructor called" << endl;
    }
    ~test2() {
        cout << " test2::destrcutor called" << endl;
    }
};

class derived :public test1, public test2 {
    test2 t2;
    test1 t1;
public:
    derived() {
        cout << " derived constructor called" << endl;
    }
    ~derived() {
        cout << "derived destructor called" << endl;
    }
};

int main() {
    derived d;
    return 0;
}

上述程序的输出显示

   test1::constructor called
   test2::constructor called
   test2::constructor called
   test1::constructor called
   derived constructor called
   derived destructor called
   test1::destrcutor called
   test2::destrcutor called
   test2::destrcutor called
   test1::destrcutor called

所以这里我的问题是它在派生类中称为成员变量的构造函数的点,因为我没有为它设置任何初始化器。

1 个答案:

答案 0 :(得分:8)

施工顺序是基础,然后是成员: -

test1::constructor called  << first base of 'derived'
test2::constructor called  << second base of 'derived'
test2::constructor called  << member of 'derived' t2
test1::constructor called  << member of 'derived' t1
derived constructor called << code in 'derived::derived'
derived destructor called  << code in 'derived::~derived'
test1::destrcutor called   << destruction of t1
test2::destrcutor called   << destruction of t2
test2::destrcutor called   << destruction of derived
test1::destrcutor called   << destruction of derived

对象只有一个析构函数,它有一个用于销毁对象的已定义顺序。这会摧毁所有成员从下到上。

然后摧毁这个阶级,并将其基础置于&#34;逆序&#34;。

每个构造函数都可以选择初始化的内容,但不能选择顺序。

a_class::a_class( params ) : 
           base_n( params ), base_n_1( params ), 
           member_1( params), member_2( params),...

这个member initialization list允许给出不同的参数来构造所有的基础和对象,但不影响顺序。它总是first_basesecond_basefirst_membersecond_member,...

这个排序是为了确保它与析构函数相反。

这些规则允许我找出哪些消息来自成员,哪些来自基地。

未从member initialization list初始化的成员仍将获得名为test2::test2的默认构造函数。一旦class / struct有一个构造函数,它们只会通过调用构造函数来生成。

Plain-old-DataPOD是简单类型,例如int,它们没有构造函数。它们未被初始化(无论记忆中留下什么价值)。