new对象时,类名后加括号与不加括号的区别
2015-10-14 08:22
435 查看
原文地址如下:http://www.cnblogs.com/Braveliu/p/4263145.html
关于默认构造函数,请参见随笔《类中函数》
请看测试代码:
至此足以。
【2】加括号与不加的区别
(1)加括号
1. 若括号为空,即无实参项,那么理解为调用默认构造函数;
2. 若括号非空,即有实参项,可以理解为调用重载构造函数,或默认复合构造函数。
(2)不加括号
调用默认构造函数,或默认复合构造函数。
关于默认构造函数,请参见随笔《类中函数》
请看测试代码:
1 #include <iostream> 2 using namespace std; 3 4 // 空类 5 class empty 6 { 7 }; 8 9 // 一个默认构造函数,一个自定义构造函数 10 class Base 11 { 12 public: 13 Base() 14 { 15 cout << " default Base construct " << endl; 16 m_nValue = 100; 17 }; 18 Base(int nValue) 19 { 20 cout << " custom Base construct " << endl; 21 m_nValue = nValue; 22 }; 23 24 private: 25 int m_nValue; 26 }; 27 28 // 一个默认复合构造函数 29 class custom 30 { 31 public: 32 custom(int value = 100) 33 { 34 cout << " default && custom construct " << endl; 35 m_nValue = value; 36 } 37 38 private: 39 int m_nValue; 40 }; 41 42 void main() 43 { 44 empty* pEmpty1 = new empty; 45 empty* pEmpty2 = new empty(); 46 47 Base* pBase1 = new Base; 48 Base* pBase2 = new Base(); 49 Base* pBase3 = new Base(200); 50 51 custom* pCustom1 = new custom; 52 custom* pCustom2 = new custom(); 53 54 delete pEmpty1; 55 delete pEmpty2; 56 57 delete pBase1; 58 delete pBase2; 59 delete pBase3; 60 61 delete pCustom1; 62 delete pCustom2; 63 } 64 // Result: 65 /* 66 default Base construct 67 default Base construct 68 custom Base construct 69 default && custom construct 70 default && custom construct 71 */
至此足以。
【2】加括号与不加的区别
(1)加括号
1. 若括号为空,即无实参项,那么理解为调用默认构造函数;
2. 若括号非空,即有实参项,可以理解为调用重载构造函数,或默认复合构造函数。
(2)不加括号
调用默认构造函数,或默认复合构造函数。
相关文章推荐
- 【视频教程】使用UIAutomation开发软件外挂
- windows 同步机制
- Git使用教程3:MyEclipse+Egit+GitHub实现代码托管 【下】
- TPP 协定可能是对互联网最可怕的事
- [c++] LeetCode Two Sum问题
- vijosP1413 Valentine’s Present
- 过滤器类
- MoinMoin install in apache (win)
- 【视频教程】使用UIAutomation开发软件外挂
- 大数加法算法
- linux 下窗口管理系统
- 一个简单自定义View控件
- 设计模式(Facade)状态(注意事项)
- 蓝懿 iOs 刘国斌 iOS
- 财富之花、财富果实和我们
- AIDL通信原理
- 模板方法模式(Template method)
- UVa 10908 - Largest Square
- 状态栏修改颜色
- AngularJS Provider/Service/Factory 使用