起初我在MSDN上看到一个程序。
例如:
#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;
}
对它的解释是:
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.
存在从参数类型(double
)到Money
的转换,而我不知道的是为什么会发生隐式转换。
再深入思考一下,我们假设一个函数需要一个类型的对象作为参数,而这个对象的构造函数需要一个参数,在调用函数的时候,是否可以提供这个参数。
最佳答案
[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. [..]
Money
显然可以从 double
初始化,因为您编写了一个构造函数来执行此操作。
但是,可以通过向该构造函数添加 explicit
关键字来禁止此类隐式转换:
explicit Money(double _amount) : amount{ _amount } {};
现在您必须在函数调用表达式中将 double
显式转换(或“强制转换”)为 Money
:
display_balance(static_cast<Money>(49.95));
关于C++:隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090216/