如果转换后的类型由于基类匹配而允许函数调用,我的编译器 (GCC 4.7) 似乎不会发出隐式类型转换,即转换结果 A
是 AB
。
class AB {};
class A: public AB
{
public:
A(float i) {}
A() {}
A(const A& rhs) {}
A(A&& rhs) {}
};
AB operator*(const AB& lhs,const AB& rhs)
{
// Return default constructed AB
}
void foo() {
A a;
auto tmp = 2.0 * a; // This fails because no conversion rule was found.
}
这是C++语言的特性吗?如果是,在什么情况下不匹配基类会更好。
请不要回答说可怜的编译器有那么多事情要做,而且与基类匹配会太多。
编辑
c.cc:51:20: error: no match for ‘operator*’ in ‘2.0e+0 * a’
c.cc:51:20: note: candidate is: c.cc:42:1: note: AB operator*(const
AB&, const AB&) c.cc:42:1: note: no known conversion for argument 1
from ‘double’ to ‘const AB&’ c.cc:51:20: error: unable to deduce
‘auto’ from ‘<expression error>’
最佳答案
Please, don't answer that the poor compiler has so much to do, and it would be too much to match against base classes.
不,但我要告诉你的是,可怜的编译器有太多事情要做,要匹配所有潜在的派生类(或通过第三种类型的其他转换)会太多
您的代码中的问题不是来自 A
的upcast至 AB
,编译器很乐意这样做,但事实上它无法转换 2.0
到AB
.允许的转换集是有限的,并且产生有限的工作集。当您调用运算符时,它会找到一个需要两个 AB
的匹配项对象,它不知道如何直接转换 double
进入AB
.很明显,它可以创建一个 A
temporary 然后从它向上转换,因为它向上转换了第二个参数。对于不知道从 A
派生出多少潜在类型的编译器来说,这并不明显。 (考虑单独编译的其他翻译单元)甚至可以从 double
构建的不相关类型并将转换运算符转换为 AB
关于c++ - 隐式类型转换看不到基类匹配。错误或功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232636/