博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
构造函数调用规则
阅读量:4695 次
发布时间:2019-06-09

本文共 2327 字,大约阅读时间需要 7 分钟。

首先我们知道只要创建一个类编译器会提供三个默认函数

1.默认构造函数 (无参,空实现) 

2.默认析构函数(无参,空实现)

3.默认拷贝构造函数,对值属性进行拷贝

调用规则如下

1.如果我们定义有参构造函数,编译器不会提供默认构造函数,但提供默认拷贝构造函数

2.如果用户定义了拷贝构造函数,编译器将不会提供其他构造函数

1 #include
2 using namespace std; 3 4 class person 5 { 6 public: 7 person() 8 { 9 puts("默认构造函数调用");10 }11 12 person(const person &p)13 {14 m_age = p.m_age; 15 puts("拷贝构造函数调用");16 }17 18 person(int age)19 {20 m_age = age;21 puts("有参构造函数调用");22 }23 24 ~person()25 {26 puts("析构函数调用");27 }28 29 int m_age;30 };31 32 void test()33 {34 person p;35 p.m_age = 18;36 person p2(p);37 cout << p2.m_age << endl; 38 }39 40 int main()41 {42 test();43 return 0;44 }
View Code

1 #include
2 using namespace std; 3 4 class person 5 { 6 public: 7 person() 8 { 9 puts("默认构造函数调用");10 }11 12 // person(const person &p)13 // {14 // m_age = p.m_age; 默认拷贝构造函数会执行这里,把所有值属性拷贝 15 // puts("拷贝构造函数调用");16 // }17 18 person(int age)19 {20 m_age = age;21 puts("有参构造函数调用");22 }23 24 ~person()25 {26 puts("析构函数调用");27 }28 29 int m_age;30 };31 32 void test()33 {34 person p;35 p.m_age = 18;36 person p2(p);37 cout << p2.m_age << endl; 38 }39 40 int main()41 {42 test();43 return 0;44 }
View Code

下面代码证明了定义有参构造函数,编译器不会提供默认构造函数,但提供默认拷贝构造函数

1 #include
2 using namespace std; 3 4 class person 5 { 6 public: 7 person() 8 { 9 puts("默认构造函数调用");10 }11 12 // person(const person &p)13 // {14 // m_age = p.m_age; 默认拷贝构造函数会执行这里,把所有值属性拷贝 15 // puts("拷贝构造函数调用");16 // }17 18 person(int age)19 {20 m_age = age;21 puts("有参构造函数调用");22 }23 24 ~person()25 {26 puts("析构函数调用");27 }28 29 int m_age;30 };31 32 void test()33 {34 person p;35 p.m_age = 18;36 person p2(p);37 cout << p2.m_age << endl; 38 }39 40 void test01()41 {42 person p(22);43 person p2(p);44 cout << p2.m_age << endl;45 } 46 int main()47 {48 //test();49 test01();50 return 0;51 }
View Code

关于第二个规则,如果你可以把除了拷贝构造函数的其他构造函数去掉,你运行是报错的

说明如果用户定义了拷贝构造函数,编译器将不会提供其他构造函数

转载于:https://www.cnblogs.com/mch5201314/p/11602407.html

你可能感兴趣的文章
深入理解 OUI(Oracle Universal Installer)
查看>>
springboots 配置文件
查看>>
一文搞定MySQL的事务和隔离级别
查看>>
手机网站——前端开发布局技巧汇总
查看>>
[转]FTP协议的分析和扩展
查看>>
位运算解决“一个数组中,只有一个数字出现n次,其他数字出现k次”问题
查看>>
CCArray
查看>>
将node-expat扩展编译至node.exe中
查看>>
列表(list)元组(tuple)字典(dictionary)集合(set)
查看>>
Github 配置 SSH
查看>>
Refresh Baidu Zhidao Evaluate Num 1.0
查看>>
数据库插入使用参数的方法 一般步骤
查看>>
Production Order System Status
查看>>
python中将字典转换成定义它的json字符串
查看>>
MAMP pro mac 本地集成环境 php sal apache等集成软件
查看>>
PHP笔记
查看>>
C++ 文件和流
查看>>
jquery.fileupload.js 多文件上传
查看>>
BroadcastReceiver概述
查看>>
i686和x86_64的区别
查看>>