我的类遇到了问题,将一个 const 对象(多态结构)传递给一个显式构造函数,该构造函数接受对该多态结构的基类的 const 引用。这是示例(这不是我的代码,这里是为了解释)
class Base
{
...
}
class Derived:public Base
{
...
}
class Problem
{
Problem(const Base&);
...
}
void myFunction(const Problem& problem)
{
...
}
int main()
{
//explicit constructor with non const object
Derived d;
Problem no1(d); //this is working fine
myFunction(no1);
//implicit constructor with const object
Problem no2=Derived(); //this is working fine, debugged and everything called fine
myFunction(no2); //is working fine
//explicit constructor with const object NOT WORKING
Problem no3(Derived()); //debugger jumps over this line (no compiler error here)
myFunction(no3); //this line is NOT COMPILING at all it says that:
//no matching function for call to myFunction(Problem (&)(Derived))
//note: candidates are: void MyFunction(const Problem&)
}
似乎只有当我将 Derived 对象显式转换为其基类 Base 时,它才能与第二个版本(显式构造函数调用 Problem)一起正常工作,如下所示:
Problem(*(Base*)&Derived);
我没有意识到隐式调用和显式调用 Problem 类的构造函数之间的区别。谢谢!