Why does float argument fit to int function parameter?

前端 未结 1 1052
暗喜
暗喜 2021-01-24 22:10

Please, look at this code:

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

int main() {
  A x = 7; // 1
  A y = 6.7; //          


        
1条回答
  •  孤街浪徒
    2021-01-24 23:06

    cppreference has 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.

    Finding A(int) to be callable with a standard conversion, the compiler inserts the necessary step to make the code work. It's the same rule that allows int x = 1.1 to compile

    If this behavior is undesirable you can forbid it with an =delete

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

    0 讨论(0)
提交回复
热议问题