Вопрос

I'm creating a Money class for a school assignment. I've defined a conversion from Money to double, I have a constructor for Money that takes an int, another constructor takes a double, and I've overloaded the "+" operator to add together two objects of type Money. The error message comes up when I try to do something like myMoney + 10 where my myMoney is an object of type Money, and 10 is obviously an integer. Here's the rest of the relevant code:

class Money {
private:
    int dollars;
    int cents;
public:
    Money(double r);
    Money(int d) : dollars(d), cents(0) {}
    operator double();
}

Money operator+(Money a, Money b) {
    double r = double(a) + double(b);
    return Money(r);
}

Money::operator double() {
    return dollars+double(cents)/100;
}

Money::Money(double r) {
    ...
}

The program actually works if I try Money(double(myMoney)+10) and also if I make both constructors explicit, but I'm not sure I understand what's happening with the automatic conversions otherwise. Can anyone explain this behavior?

Это было полезно?

Решение

MyMoney + 10

Since there's no operator+(Money, int), some conversions have to be made here. The compiler could convert the Money to a double, then convert the 10 to a 'double' and choose the built-in operator+(double,double), or it could convert the int to Money and choose your operator+(Money,Money).

Другие советы

The problem as seen by the compiler and as Benjamin points out, is that there are two conversion sequences that lead to different valid sets of arguments to operator+ overloads. But this is actually an indication of a deeper problem with the design. Implicit conversions should be used scarcely, and having implicit conversions from and two different types is a recipe for problems.

Consider making your constructors explicit, and either making the conversion operators also explicit (C++11 language feature), or remove them and provide named conversions (through member functions rather than operators) as is the case in std::string::c_str().

Does it really makes sense that anything is turned automatically into money? And that just as easily it turns into dust? Learn to let the compiler help you in detecting logic issues by avoiding implicit conversions that weaken your type system.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top