下面程序f()被调用时,输出是什么??
#include <iostream>
#include <string>
using namespace std;
class Number
{
public:
string type;
Number():type("void"){};
explicit Number(short):type("short"){}
Number(int):type("int"){}
};
void show(const Number& n)
{
cout<<n.type<<endl;
}
int main()
{
short s = 24;
show(s);//这里发生了隐式类型转换,将short类型的s隐式转换成了Number类型
}
编译运行的结果是:
int
show(s)中的s为short类型,其值为24,因为首先检查参数为short的构造函数能否被隐式转换。由于参数为short的构造函数被声明为显示调用(explicit),因此不能被隐式转换,于是24只能转换成int类型,此时检查参数为int类型的构造函数能否被隐式转换,由于参数为int的该构造函数没有被声明为显示调用,因此可以调用此构造函数构造出一个临时对象。
关于这个问题,还有下面的代码
class Test1
{
public:
Test1(int n){num = n;}
private:
int num;
};
class Test2
{
public:
explicit Test2(int n){num = n;}
private:
int num;
};
int main()
{
Test1 t1 = 12; //隐式调用其构造函数,成功
Test2 t2 = 13; //编译不通过,不能隐式调用其构造函数
Test2 t3(14); //显示调用成功
return 0;
}