#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
class Test
{
public:
Test(int i)
{
cout<<"Test(int i)"<<endl;
}
Test(const Test& obj)
{
cout<<"Test(const Test& obj)"<<endl;
}
/*
explicit Test(const Test& obj)
{
cout<<"Test(const Test& obj)"<<endl;
}
*/
~Test()
{
cout<<"~Test()"<<endl;
}
};
void func()
{
//C++编译器会尝试各种手段尝试让程序通过编译、
//方式一:尽力匹配重载函数
//方式二:尽力使用函数的默认参数
//方式三:尽力尝试调用构造函数进行类型转换
Test t1(5);
Test t2 = 5;
Test t3 = Test(5);//当把拷贝构造函数 用explicit关键字用于阻止编译器对构造函数的调用 时, Test t2 = 5;Test t3 = Test(5);调用的时候报错,说明他们不只简单
//调用Test(int i) ;
/*
Test t2 = 5;的编译原理:
1.默认情况下,字面量5的类型为int,因此5无法直接用于初始化Test对象;
2.但是编译器在默认情况下可以自动调用构造函数
3.于是编译器尝试调用Test(int)生成一个临时对象;
4.之后调用拷贝构造函数Test(const Test&)用临时对象对对象t2进行初始化。
*/
}
int main(int argc, char** argv) {
func();
//y运行结果为:
/*
Test(int i)
Test(int i)
~Test()
~Test()
~Test()
三种调用的构造函数一样,说明编译器对构造函数的调用进行了优化处理;
*/
return 0;
}
C++学习笔记16-2 编译器对构造函数的调用处理
最新推荐文章于 2023-07-20 20:05:09 发布