为什么float参数适合int函数参数? [英] Why does float argument fit to int function parameter?

查看:185
本文介绍了为什么float参数适合int函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码:

#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); 构造函数。
当完全允许编译器将一种参数类型转换为另一种参数类型以调用相应的构造函数时?

It actually compiles although there is no A(double a); constructor. When exactly compiler is allowed to convert one argument type to another to call corresponding constructor?

推荐答案

cppreference具有标准转化列表。您感兴趣的是浮动-积分转换部分,该部分也可以在 N4140 4.9 / 1

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


浮点类型的prvalue可以转换为任何整数类型。小数部分被截断,即小数部分被丢弃。

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 进行编译

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;
};    

这篇关于为什么float参数适合int函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆