我们都知道当user没有为一个不同的类(不符合后面讨论的几种case)定义任何构造函数时,编译器会隐式的合成一个默认构造函数,但是这个函数是空的,什么操作也不做。这就是implicit trivial default constructors。
但是编译器有时候也会合成另外一种默认构造函数implicit nontrivial default constructors,这种函数不是空的,他们会做一些操作,现在就看看这几种情况。
- 1. class中含有一到多个其他class的对象,这些class有定义默认构造函数,这样的话,编译器就开始工作啦。
class bear { public: int i; bear() { i=0; } void display() { cout<<"bear 's display:"<<i<<endl; } }; class malebear { public: int j; bear a; void display() { a.display(); cout<<"malebear 's display:"<<j<<endl; } }; void classtest() { bear a; malebear b; a.display(); b.display(); }
- 2.class继承了有默认构造函数的基类。
class femalebear : public bear { public: int k; void display() { bear::display(); cout<<"femalebear 's display:"<<k<<endl; } }; void classtest() { bear a; femalebear b; a.display(); b.display(); }
- 3.class中有虚函数。
class dog { public: int t; virtual void display() { cout<<"dog 's display:"<<t<<endl; } }; class maledog: public dog { public: int s; void display() { cout<<"maledog 's display:"<<s<<endl; } }; void classtest() { maledog a; dog &b = a; a.display(); b.display(); }
- 4.class继承了没有默认构造函数的虚基类。
class dog { public: int t; virtual void display() { cout<<"dog 's display:"<<t<<endl; } }; class femaledog: virtual public dog { public: int q; void display() { cout<<"femaledog 's display:"<<q<<endl; } }; class bigfemaledog: public femaledog { public: int r; void display() { cout<<"femaledog 's display:"<<q<<endl; } }; void classtest() { bigfemaledog a; dog &b = a; a.display(); b.display(); }