C++:隐式转换

标签 c++

起初我在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/

相关文章:

c++ - 构建文件夹和makefile

c++ - boost program_options 接受最后一个标志后的所有值

c++ - 如何在另一个项目的dll中添加调用函数

c++ - linux 中的 wmain 或 _tmain 替代品是什么?

C++ 列表迭代器不访问列表的内容

c++ - 未解析的外部符号 LNK2019

c++ - 使用来自 SOCI 的匿名 PL SQL block 调用 PLsql 脚本

c++ - 在 Matlab 中加载 .dll 导致 'type not found' 问题

c++ - 为什么要重新定义函数命名空间?

c++ - NCurses “mvwaddch”需要澄清