我只是想了解它是如何发生的,因为它是新的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
所以在这里我的问题是,在什么点它叫做成员变量的构造函数在派生类中,因为我还没有把任何初始化为同。
由于您是C++新手,因此使用继承和多态性时要注意的一件事是确保您从您派生的类正在使用虚拟析构函数,这将为您节省大量未来的麻烦!由于派生从test1和test2继承,所以test1和test2中的两个析构函数都应该是虚拟的!这可能不是必须的,但将派生析构函数虚拟为好也是一种好的做法!这有助于保持对象被销毁的顺序,以便类中的指针保持有效,特别是在处理动态或新内存时。 –