为什么构造函数在使用 CHAR 类型的参数调用时选择类型 INT 而不是 SHORT?

Why does constructor choose type INT instead of SHORT when invoked with a parameter of type CHAR?

可以看出,在下面的代码中,正在调用参数类型为 int 的构造函数。我知道 int 在这里没问题。但为什么不 short?因为 'A' 的 ASCII 值给出了 short 可以容纳的 65。

根据什么条件调用参数为int的构造函数?


#include<iostream>

class RightData
{
    int x; 
    public:
    RightData(short data)
    {
        cout<< "Short" << endl;
    }
    RightData(int data)
    {
        cout<< "Int" << endl;
    }
    RightData(float data)
    {
        cout<< "Float" << endl;
    }
    ~RightData() 
    {
        cout<< "Final";
    }
};
int main()
{
    RightData *ptr = new RightData('A');
    return 0; 
}

编译器始终选择 best matching 重载解决方案。

你的情况:

类型提升为:

  1. char、unsigned char 或 short 可以提升为 int。例如 void f(int);可以匹配 f('a');
  2. 浮点数可以升级为双精度数。
  3. bool 可以提升为 int(FALSE 算作 0,TRUE 算作 1)。

integral promotion is int (not short) for char; and promotions (e.g. char -> int) have higher ranking than other conversions (e.g. char -> short) in overload resolution的结果。

prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int).

  • signed char or signed short can be converted to int;
  • unsigned char, char8_t (since C++20) or unsigned short can be converted to int if it can hold its entire value range, and unsigned int otherwise;
  • char can be converted to int or unsigned int depending on the underlying type: signed char or unsigned char (see above);

和(强调我的)

Note that all other conversions are not promotions; for example, overload resolution chooses char -> int (promotion) over char -> short (conversion).

隐式转换时,编译器遵循此 ranking:

  1. 完全匹配
  2. 晋升
  3. 转化

因为 charint 是积分 促销 ,它优先于 charshort转换.

来自 here(强调我的):

char can be converted to int or unsigned int depending on the underlying type: signed char or unsigned char