C++构造函数隐式类型转换
C++ constructor implicit type conversion
假设我有这个代码:
class A {
public:
A(int y) { cout << y; }
};
int main() {
A a(1.5);
return 0;
}
即使 1.5 是 float
,此代码也有效 returns 1. float
被隐式转换为 int
。为什么它没有抛出异常?构造函数是否取决于参数的数量或它们的类型?我在哪里可以读到这篇文章?
因为这样implicit conversion(从double
到int
)是允许的。
Floating–integral conversions
- A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavior is undefined (even when the destination type is unsigned, modulo arithmetic does not apply).
如果你不希望这样的构造发生,你可以添加一个带double
的构造函数并将其标记为delete
。例如
class A {
public:
A(double) = delete;
A(int y) { cout << y; }
};
顺便说一句:1.5
是 double
,而不是 float
。
假设我有这个代码:
class A {
public:
A(int y) { cout << y; }
};
int main() {
A a(1.5);
return 0;
}
即使 1.5 是 float
,此代码也有效 returns 1. float
被隐式转换为 int
。为什么它没有抛出异常?构造函数是否取决于参数的数量或它们的类型?我在哪里可以读到这篇文章?
因为这样implicit conversion(从double
到int
)是允许的。
Floating–integral conversions
- A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavior is undefined (even when the destination type is unsigned, modulo arithmetic does not apply).
如果你不希望这样的构造发生,你可以添加一个带double
的构造函数并将其标记为delete
。例如
class A {
public:
A(double) = delete;
A(int y) { cout << y; }
};
顺便说一句:1.5
是 double
,而不是 float
。