问题以下程序的输出是什么?
# includeiostreamusingnamespacestd; 语音(长); 常数字符*; int main () ) f ) 1? 0:1; 返回0; }voidf(long ) ) { cout 'long' endl; } voidf (常数char * ) { cout 'const char*' endl; }
很遗憾,在g中编译失败了:
$ g conditional_exp.cpp
conditional _ exp.CPP : in function‘int main’:
conditional _ exp.CPP :10:错误:调用重载的“‘f(int )”有歧义
conditional_exp.cpp:5:备注:替代为voidf(longint )
conditional_exp.cpp:6:备注: voidf(constchar* ) ) ) ) ) ) ) )。
条件式(1? 0:1 )的类型是什么?
couttypeid(1? 0:1(.name ) ) endl;
上面的输出字符I表示表达式的类型为int
调用f(1)时,最上面的程序编译正常,输出为long
调用f(0)时,顶部的程序也会报告相同的编译错误。 也就是说,从编译器来看) 1? 0:1 )与0没有变化。
文字0的类型为int,没有参数为int的函数。 需要隐式类型转换。 0可以转换为long,也可以作为空指针转换为const char*,产生二义性,可以编译并报告错误。
调用如下:
常数char * p=null; f (p==空? 0:1; eclipse继续呈现二义性,但编译没有报告错误,也没有警告,程序输出为长(0:1的结果是发生了编译错误,这里是否成功编译? )
编译和运行时的结果如此不同,是不是运行的规则有点不同呢?
结果显示,编译要执行更严格的检查,报告错误是要注意编码器,如果执行了很可能出现错误的操作,它将根据规则,隐式地将int转换为long,并调用正确的函数。
以下是一些尝试的总结。
f(1? 0:1; //compileerrorf(0; //compileerrorf(1? 2:1; //callf(long ) const char* p=NULL; f (p==空? 0:1; //eclipse complain,compile succeed,callf(long ) f ) f(NULL; //compileerrorf(0L; //callf(long ) f () constchar* )0); //callf (常数字符* ) )。
如果现在要添加函数重载:
voidf(int ) {cout 'int' endl; }
没有compile error和eclipse complain。 类型为int,找到了准确的函数原型。 不需要类型转换:
f(1? 0:1; //callf(int ) f ) 0; //callf(int ) f ) 1? 2:1; //callf(int ) const char* p=NULL; f (p==空? 0:1; //callf(int ) f ) f (空值; //callf(long ) f ) 0L; //callf(long ) f () constchar* )0); //callf (常数字符* ) )。
建议
调用时,在0后面加上l后缀,如下所示。
f(1? 0L:1;
更好的方法是添加参数int的函数重载。
voidf(intI ) f ) )长) I; }
版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。