实参类型转换

在实现函数重载时,通常会遇到如何选择函数的问题

为了确定最佳匹配,编译器将实参类型到相应形参类型的转换划分等级,转换等级降序如下:

1)精确匹配,实参与形参类型相同;

2)通过类型提升实现的匹配;

#include <iostream>
using namespace std;
void display(int num)
{
    cout<<"recall function display(int num): "<<num<<endl;
}
void display(short num)
{
     cout<<"recall function display(short num): "<<num<<endl;
}
void display(double num)
{
     cout<<"recall function display(double num): "<<num<<endl;
}
int main()
{
    char cDisplayNum = 'a';
    display(cDisplayNum);
    return 0;
}
 

上述例子展示了类型提升。C++语言为内置类型提供了一组转换规则,其中最常用的是算术转换,算术转换规则定义了一个类型转换层次,改层次规定了操作数应该按什么次序转换为表达式中最宽的类型。如对于小于int的整型,包括char、signed char、unsigned char、short和unsigned short都会提升为int类型。

3)通过标准转换实现的匹配;

    1.指针转换;2.转换为bool类型;3.算术类型与bool类型的转换; 4.转换与枚举类型;5.转换为const对象; 6.有标准库类型定义的转换。

4)通过类类型转换实现的匹配。

 

posted @ 2019-05-05 22:01  风雪之殇  阅读(442)  评论(0编辑  收藏  举报