如何防止隐式转换double - > int? [英] How do I prevent an implicit cast double -> int?
问题描述
问题如上,更多细节如下:
Question as above, more details below:
我有一个类 Money
来处理...好了,你猜到了什么。我非常严格不允许 Money
和 double
进行交互(*),因此以下代码
I have a class Money
to deal with... well, you guessed what. I am very strict about not allowing Money
and double
to interact(*), so the following code is not possible:
现在我正在考虑允许 Money
与 int
,如你有6块蛋糕,每个$ 4.50(所以去去找到更便宜的蛋糕某处) / p>
Now I'm thinking about allowing multiplication of Money
with int
, as in "you have 6 pieces of cake for $4.50 each (so go and find cheaper cake somewhere)."
class Money
{
Money();
Money( const Money & other );
explicit Money( double d );
...
Money & operator*=( int i );
...
}
inline const Money operator*( const Money & m, int i ) { return Money( m ) *= i; }
inline const Money operator*( int i, const Money & m ) { return Money( m ) *= i; }
这很好,但 ...
,C ++会从 double
到 int
隐藏转换 ,所以突然我的第一个代码片段编译。我不想要。在这种情况下有没有办法防止隐式强制转换?
That works fine, but...
unfortunately, C++ does implicit casts from double
to int
, so suddenly my first code snippet will compile. I don't want that. Is there any way to prevent implicit casts in this situation?
谢谢! - Robin
Thanks! -- Robin
(*)原因:我有很多遗留代码处理所有 Money
double
,我不希望这些类型混淆,直到所有运行 Money
。
(*) Reason: I have lot's of legacy code that handles all Money
-related stuff with double
, and I don't want those types confused until everything run with Money
.
编辑:为Money添加构造函数。
Added constructors for Money.
编辑:感谢大家,为您的答案。几乎所有的人都是伟大的和有益的。 R. Martinho Fernandes的评论你可以做 inline const Money operator *(const Money& m,double d)= delete;
其实是答案我切换到支持C ++ 11的编译器)。 Kerrek SB给了一个很好的无C ++ 11的替代品,但是我最终使用的是Nicola Musatti的overload long
方法。这就是为什么我把他的答案标记为答案(也因为所有有用的想法出现作为评论他的答案)。
Thanks, everyone, for your answers. Almost all of them were great and helpful. R. Martinho Fernandes' comment "you can do inline const Money operator*( const Money & m, double d ) = delete;
" was actually the answer (as soon as I switch to a C++11-supporting compiler). Kerrek SB gave a good none-C++11 alternative, but what I ended up with using is actually Nicola Musatti's "overload long
" approach. That's why I'm flagging his answer as "the answer" (also because all the useful ideas came up as comments to his answer). Again, thanks!
推荐答案
您可以为扩充赋值运算符的私有重载添加声明:
You could add a declaration for a private overload of your augmented assignment operator:
private:
Money & operator*=( double i );
这篇关于如何防止隐式转换double - > int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!