为什么 float 参数适合 int 函数参数?

Why does float argument fit to int function parameter?

请看这段代码:

#include <iostream>
class A {
  public:
    int my;
    A(int a=0) : my(a) { }
};

int main() {
  A x = 7; // 1
  A y = 6.7; // 2
  std::cout << x.my << " " << y.my << "\n";
}

虽然没有 A(double a); 构造函数,但它实际上可以编译。 究竟什么时候允许编译器将一种参数类型转换为另一种参数类型以调用相应的构造函数?

cppreference 有 a list of standard conversions. Of interest to you is the Floating - integral conversions section which can also be found in N4140 4.9/1

A prvalue of floating-point type can be converted to prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded.

发现 A(int) 可通过标准转换调用,编译器插入必要的步骤以使代码工作。允许 int x = 1.1 编译

的规则相同

如果这种行为是不可取的,你可以用 =delete

来禁止它
class A {
  public:
    //...
    A(int a);
    A(double) =delete;
};