关于nontrivial default constructor(二)
2017-03-01 19:38
267 查看
情况一:
如果一个没有任何构造函数的class派生自一个带有默认构造函数的base class,那么派生类的构造函数被视为nontrivial,因此会被编译器合成出来。它将调用基类的默认构造函数。class Base { public: Base() { cout << "Base constructor ..." << endl; } }; class Derived : public Base { public: }; int main(void) { Derived derived; return 0; }结果如下:
情况二:
如果设计者提供多个构造函数,但就是没有default constructor, 编译器会扩张每一个构造函数。但它不会合成一个新的默认构造函数。class Base { public: Base() { cout << "Base constructor ..." << endl; } }; class Derived : public Base { public: int a; Derived(int x) { a = x; } }; int main(void) { //Derived derived; //出现编译错误 Derived derived(10); cout<<derived.a<<endl; return 0; }
当然,如果此时定义了默认构造函数,如下,
class Base { public: Base() { cout << "Base constructor ..." << endl; } }; class Derived : public Base { public: int a; Derived(int x) { a = x; } Derived() { cout<<"user-defined default constructor ..."<<endl; a = 0; } }; int main(void) { Derived derived0; cout<<derived0.a<<endl; Derived derived1(10); cout<<derived1.a<<endl; return 0; }
如果类内还存在着带有默认构造函数的member class object,则这些默认构造函数也会被调用——在基类构造函数之后
class Base { public: Base() { cout << "Base constructor ..." << endl; } }; class B { public: B() { cout << "B constructor ..." << endl; } }; class Derived : public Base { public: int a; B b; Derived(int x) { a = x; } Derived() { cout<<"user-defined default constructor ..."<<endl; a = 0; } }; int main(void) { Derived derived0; cout<<derived0.a<<endl; Derived derived1(10); cout<<derived1.a<<endl; return 0; }结果如下:
相关文章推荐
- 关于nontrivial default constructor(一)
- [C++]《深度探索C++对象模型》读书笔记 - nontrivial default constructor
- 深度探索C++对象模型-----编译器’何时‘自动合成nontrivial default constructor
- nontrivial default constructor(重要的默认构造函数)---四种情况
- Android Fragment avoid non-default constructors in fragments use a default constructor plus fragment
- 【错误】Error:Error: Avoid non-default constructors in fragments: use a default constructor plus
- 开发中碰到的问题:Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArg
- What is a non-trivial constructor in C++?(转载)
- Error:(43, 9) Error: Avoid non-default constructors in fragments: use a default constructor plus Fra
- 关于vc6.0中SetDefaultPrinter不能被编译器识别的问题
- 关于 socke t设置为非阻塞(non-blocking)状态
- 关于Apache: [warn] _default_ VirtualHost overlap on port 80, the first has precedence Error and Solution的解决方案
- PHP关于VC9和VC6以及Thread Safe和Non Thread Safe版本选择的问题
- 关于PHP VC9,VC6,Thread Safe,Non Thread Safe
- 关于《ASP.NET2.0网站开发实例教程》中1.1.4 Default.aspx页面的实现的说明
- PHP关于VC9和VC6以及Thread Safe和Non Thread Safe版本选择的问题
- 关于未对齐指针释放问题(Non-aligned pointer being freed)
- A constructor that supplies default arguments for all its parameters also defines the default constructor.
- 关于JS中的constructor与prototype
- (原創) 為什麼derived-class會去執行base-class的default constructor? (C/C++)