为什么下面的代码调用了Child类的converter构造函数?
我的意思是,它通过 Child 转换器构造函数自动将 Base 转换为 Child。下面的代码编译,但它不应该不编译因为我没有提供bool Child::operator!=(Base const&)
吗?
class Base
{
};
class Child : public Base
{
public:
Child() {}
Child(Base const& base_) :
Base(base_)
{
std::cout <<"should never called!";
}
bool operator!=(Child const&)
{
return true;
}
};
void main()
{
Base base;
Child child;
if(child != base)
std::cout << "not equal";
else
std::cout << "equal";
}
最佳答案
带有签名Child(Base const& base_)
的函数不是复制构造函数(右边的类型与左边的不同)。编译器可以隐式使用该构造函数将一种类型强制转换为另一种类型,以便您在 main
中进行比较。为防止此标记构造函数 explicit
。
关于C++ 为什么要隐式调用转换器构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2451214/