我怀疑C ++在必须进行数学运算时如何转换类型。
下面的代码原样(即只有转换为int而没有强制转换为double)工作和构建没有问题。如果我定义ENABLE_DOUBLE_CAST
没有构建并抱怨operator*
。你知道为什么吗?
我怀疑的是2:
由于
AFG
class CA{
int _m;
public:
CA( int a, int b ){
_m=a*b;
}
operator int (){
std::cout<< "(CA int cast)" ;
return _m;
}
#ifdef ENABLE_DOUBLE_CAST
operator double(){
std::cout << "(CA double cat)";
return 2.3 * _m;
}
#endif
};
int main( int argc, const char** argv){
CA obj_2( 10,20 );
double total_1 = 100.0 * obj_2;
double total_2 = obj_2 * 100.0;
return 0;
}
答案 0 :(得分:3)
为什么没有运算符强制转换为double,它在double之间的乘法中使用了一个int。是因为隐式演员?
是的,这是真的
它使用operator int ()
将obj_2
转换为int,然后使用内置的operator*(double, int)
为什么启用了double
的强制转换功能(增加了语法的清晰度)?
当您为班级提供operator double()
和operator int ()
时,会产生歧义,无论是将obj_2
转换为int
还是double
,因为那里是它可以使用的两个内置运算符重载,即:
operator*(double, int)
operator*(double, double)
的建议:强>
如果您想避免隐式转换和由此产生的模糊性问题,您应该为您的班级重载operator*
。
operator*(double,CA) and
operator*(CA,int)
答案 1 :(得分:1)
原因是两个演员都有不明确的代码,编译器无法决定是使用int cast还是双重演员,两者都是合法的。
关于隐式转换的规则很复杂,我不打算在这里重复它们(它实际上需要页面和页面来覆盖所有内容)。但是,如果它普遍同意将隐式强制转换添加到您的类中是一个坏主意,因为模糊问题就像您所看到的那样。如果要将CA与operator *一起使用,那么最好为您的类定义operator *。 E.g。
CA operator*(CA x, CA y)
{
...
}
CA operator*(CA x, int y)
{
...
}
CA operator*(CA x, double y)
{
...
}
CA operator*(int x, CA y)
{
...
}
CA operator*(double x, CA y)
{
...
}