将对象初始化为另一个类的成员 我只是想了解它是如何发生的,就像C++的新的一样。

将对象初始化为另一个类的成员 我只是想了解它是如何发生的,就像C++的新的一样。,c++,C++,让我详细说明我的问题陈述 class test1 { public: test1() { cout << " test1::constructor called" << endl; } ~test1() { cout << " test1::destrcutor called" << endl; } }; class test2 { public: test2() {

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

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  << 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
成员初始化列表
允许为构造所有基和对象提供不同的参数,但不影响顺序。它总是
第一个基础
第二个基础
第一个成员
第二个成员

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

这些规则使我能够确定哪些信息来自成员,哪些来自基地

未从
成员初始化列表中初始化的成员仍将获得其名为
test2::test2
的默认构造函数。因为一旦
/
结构
有了构造函数,它们就只有通过调用构造函数才能存在


普通旧数据
POD
是一些简单类型,例如
int
,它们没有构造函数。由于它们是在C++中新建的,所以在使用继承和多态时要注意的一件事是确保从你派生的类使用虚拟析构函数,这将在将来为你省去很多麻烦。由于派生是从test1和test2继承的,所以test1和test2中的析构函数都应该是虚拟的!这可能不是必需的,但将派生的析构函数也设置为虚拟也是一种很好的做法!这有助于保持对象被销毁的顺序,以便类中的指针保持有效,特别是在使用动态内存或新内存时。
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
a_class::a_class( params ) : 
           base_n( params ), base_n_1( params ), 
           member_1( params), member_2( params),...