显式与隐式构造函数隐式转换调用的区别,该怎么处理

显式与隐式构造函数调用的区别看C++ & primer看晕了,为什么要分显式和隐式啊?这两者在具体的调用中,都有些什么区别?
回答1:explicit加在构造函数的前面之后,构造函数就不能被隐式的调用,否则可以隐式的被调用,举个例子楼主就懂了
A operator+(const A& a);
A::A(int x)
A A::operator+(const A& a);
a=this-& data+a.
int main()
//调用了operator+,可以正确的运行
//因为operator+要求的是两个A类型的形参,所以7会自动的被A(int x)转换为一个A的对象,然后再与a相加,而你如果在A(int x)这个构造函数前加了explicit,则这个7到a的转换不会执行,c=a+7会报错
回答2:explicit 声明显式的意义,
主要就是防止 非预期 的构造类型转换过程的发生 ~君,已阅读到文档的结尾了呢~~
扫扫二维码,随身浏览文档
手机或平板扫扫即可继续访问
拷贝构造函数
举报该文档为侵权文档。
举报该文档含有违规或不良信息。
反馈该文档无法正常浏览。
举报该文档为重复文档。
推荐理由:
将文档分享至:
分享完整地址
文档地址:
粘贴到BBS或博客
flash地址:
支持嵌入FLASH地址的网站使用
html代码:
&embed src='/DocinViewer-4.swf' width='100%' height='600' type=application/x-shockwave-flash ALLOWFULLSCREEN='true' ALLOWSCRIPTACCESS='always'&&/embed&
450px*300px480px*400px650px*490px
支持嵌入HTML代码的网站使用
您的内容已经提交成功
您所提交的内容需要审核后才能发布,请您等待!
3秒自动关闭窗口在Geeks上看到一题,很是费解:关于C++的显式/隐式调用构造和析构函数。
第一个问题:
#include &iostream&
class Test
& & Test() &{ cout && "Constructor is executed\n"; }
& & ~Test() { cout && "Destructor is executed\n"; &}
int main()
& & Test(); &// Explicit call to constructor
& & T // local object
& & t.~Test(); // Explicit call to destructor
& & return 0;
执行以上代码出现:
Constructor is executed
Destructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
但是以下代码:
#include &iostream&
class Test
& & Test() &{ cout && "Constructor is executed\n"; }
& & ~Test() { cout && "Destructor is executed\n"; &}
int main()
& & Test(); &// Explicit call to constructor
& & T // local object
& &// t.~Test(); // Explicit call to destructor
& & return 0;
去掉红色部分后,出现结果为:
Constructor is executed
Destructor is executed
Constructor is executed
但是,我调试发现其实最后的析构有执行,但是为什么没显示“Destructor is executed”这条语句呢?
第二个问题:
另外一个例子:
#include &iostream&
class Test
& & Test() &
cout && "Constructor is executed\n";&
& & ~Test()&
cout && "Destructor is executed\n"; &
& & void show() &
this-&Test::~Test(); &
int main()
& & t.show();
& & return 0;
执行代码后出现
Constructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
Destructor is executed
删掉this后:
#include &iostream&
class Test
& & Test() &
cout && "Constructor is executed\n";&
& & ~Test()&
cout && "Destructor is executed\n"; &
& & void show() &
Test::~Test(); &
int main()
& & t.show();
& & return 0;
Constructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
但是调试发现还是执行了最后的析构,也就是说析构3次了,为什么也没显示出“Destructor is executed”呢?
你在cout最后加个endl试试,感觉你是没有刷新输出导致打印的字符没有显示
--- 共有 1 条评论 ---
差不多是这个意思,而且我发现不能使用getchar或者system(“pause”),只能ctrl+f5才能正确输出,否则需要再按一次键盘,才能出现最后一个析构!
你是如何确定析构被执行了? 我感觉C++编译器并不保证一定会调用析构函数, 尤其是在要退出程序的时候.析构函数已经变得毫无意义, 有可能会被月优化掉.我不知道你的编译参数是什么, 你把所有的优化选项都关闭掉, 看看最后的结果是什么?&
--- 共有 1 条评论 ---
优化是关掉的。
然后我是在调试状态下进入代码内部,发现函数有跳到析构语句那一条。
用的什么编译器?第二第三种情况,我都比你多输出一次Destructor is executed
--- 共有 1 条评论 ---
我用的是VS2010,看来编译器有问题。
是不是只要执行了析构就会在某些编译器上显示呢?
我换个编译器试试!

我要回帖

更多关于 隐式调用拷贝构造函数 的文章

 

随机推荐