C++中的构造函数行为

-1 c++ constructor

这怎么可能??
test t2=50??? 因为t2是对象a .....所以如何使用visual studio 2008将它等于整数

class test
{
public :
 int a,b;
 test(int x=0,int y=0)
 {
  a=x;
  b=y;
 }
};


void g()
{
 test t1=test(10,20);
 test t2=50;
 cout<<t1.a<<":"<<t1.b<<endl;
 cout<<t2.a<<":"<<t2.b<<endl;
}

int main()
{
 g();
 system("pause");
}
Run Code Online (Sandbox Code Playgroud)

Nav*_*een 8

由于未定义构造函数,explicit因此编译器使用test类中定义的构造函数test通过将整数参数传递给构造函数(参数x)来创建对象.为了避免这种情况,将构造函数声明为explicit.