[英]C++: implicit conversions
At first I saw a program on MSDN. 起初,我在MSDN上看到了一个程序。
For example: 例如:
#include <iostream>
class Money
{
public:
Money() : amount{ 0.0 } {};
Money(double _amount) : amount{ _amount } {};
double amount;
};
void display_balance(const Money balance)
{
std::cout << "The balance is: " << balance.amount << std::endl;
}
int main(int argc, char* argv[])
{
Money payable{ 79.99 };
display_balance(payable);
display_balance(49.95);
display_balance(9.99f);
return 0;
}
The explanation for it is: 对此的解释是:
On the second call to display_balance, the type of the argument, a double with a value of 49.95, is not the function expects, so a conversion is needed.
在第二次调用display_balance时,参数的类型(值为49.95的double )不是函数所期望的,因此需要进行转换。
There is a conversion from the type of argument— double
to Money
, and what I don't know about it is why the implicit conversion happened. 从参数的类型有一个转换-从
double
到Money
,我不知道这是为什么隐式转换发生的原因。
Think about it more deeply, we assume that a function needs a type of object as a parameter, and the constructor of the object needs one parameter, when call to the function, whether can provide this parameter. 仔细考虑一下,我们假设一个函数需要一种对象类型作为参数,而该对象的构造函数需要一个参数,当调用该函数时,是否可以提供该参数。
[C++14: 5.2.2/4]:
When a function is called, each parameter (8.3.5) shall be initialized (8.5, 12.8, 12.1) with its corresponding argument.[C++14: 5.2.2/4]:
调用函数时,每个参数(8.3.5)应使用其相应的参数进行初始化(8.5、12.8、12.1)。 [..][..]
Money
can obviously be initialized from double
because you wrote a constructor to do exactly that. 显然,可以将
Money
从double
初始化,因为您编写了一个构造函数来实现此目的。
It is, however, possible to prohibit such implicit conversions by adding the explicit
keyword to that constructor: 但是,可以通过向该构造函数添加
explicit
关键字来禁止此类隐式转换:
explicit Money(double _amount) : amount{ _amount } {};
Now you'd have to explicitly convert (or "cast") the double
to a Money
in the function call expression: 现在,您必须在函数调用表达式中将
double
精度显式转换(或“转换”)为Money
:
display_balance(static_cast<Money>(49.95));
i think this example will help: 我认为这个例子会有所帮助:
int number;
double rate;
number =2;
rate=1.0345;
number=rate;
cout<<number<<endl; //implicit conversion //narrowing conersion //gives 1 //tried to store floating point number in integer data type variable
rate=2 // implicit conversion //widening conversion // value actually assigned is 2.0 //we are not ordering compiler to convert double data type to integer. it is automatically understood by compiler.
number=(int)rate; //explicit conversion //we are ordering compiler here to take value from rate and convert it to integer and assign it to number. //we are specific here.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.