C ++:隐式转换

时间:2015-06-27 15:14:18

标签: 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;
}

对它的解释是:

  

在第二次调用display_balance时,参数的类型, double ,值为49.95,不是函数所期望的,因此需要进行转换。

从参数类型doubleMoney的转换,我不知道的是隐式转换发生的原因。

更深入地考虑一下,我们假设一个函数需要一种对象作为参数,并且对象的构造函数需要一个参数,当调用该函数时,是否可以提供此参数。

2 个答案:

答案 0 :(得分:3)

  

[C++14: 5.2.2/4]:调用函数时,应使用相应的参数初始化每个参数(8.3.5)(8.5,12.8,12.1)。 [..]

显然可以从Money初始化

double因为您编写了一个构造函数来完成此操作。

但是,可以通过将explicit关键字添加到该构造函数来禁止此类隐式转换:

explicit Money(double _amount) : amount{ _amount } {};

现在你必须在函数调用表达式中显式转换(或“强制转换”)doubleMoney

display_balance(static_cast<Money>(49.95));

答案 1 :(得分:0)

我认为这个例子会有所帮助:

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.