why_coder
why_coder
2017-11-19 09:24

关于c++构造函数和类型转换的一个简单问题

  • c++

#include
using namespace std;

class A{
public:
A(){cout<<"constructed";}
A(int){cout<<"constructed by convert";}
A(A& a){cout<<"constructed by copy";}
~A(){cout<<"distructed";}
};
void foo(A){;}
int main(){
A a1;
A a2=A(2);
system("pause");
return 0;
}
以上是源代码,在声明a2时我想的时应该先申请一个临时变量调用带int参数的构造函数,在调用复制构造函数用这个临时变量来构造a2,再析构临时变量,应该输出的是constructed by convertconstructed by copydistructed,可实际上只输出了constructed by convert,为什么呢?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答