C++ 协变克隆函数
这个问题与最近的一个问题有关 以代码为例:C++ 协变克隆函数,c++,c++11,C++,C++11,这个问题与最近的一个问题有关 以代码为例: #include <iostream> #include <typeinfo> class Base { public: virtual Base * clone() { Base * bp = new Base ; return bp ; } }; class Derived: public Base { public: Derived * clone()
#include <iostream>
#include <typeinfo>
class Base
{
public:
virtual Base * clone()
{
Base * bp = new Base ;
return bp ;
}
};
class Derived: public Base
{
public:
Derived * clone() override
{
Derived * dp = new Derived ;
return dp ;
}
};
int main()
{
Base * bp = new Derived;
auto funky = bp->clone();
std::cout << typeid(funky).name() << std::endl;
}
#包括
#包括
阶级基础
{
公众:
虚拟基*克隆()
{
基准*bp=新基准;
返回bp;
}
};
派生类:公共基
{
公众:
派生的*克隆()覆盖
{
衍生*dp=新衍生;
返回dp;
}
};
int main()
{
基准*bp=新衍生的;
auto funky=bp->clone();
std::cout clone()
应该是派生的*
,而不是基本的*
声明
auto funky = bp->clone();
相当于
Base* funky = bp->clone();
因为Base::clone
返回一个Base*
检查该指针的类型,然后生成Base*
当
Base
类型是多态的时,检查指针对象的类型是另一回事。在所展示的代码中Base
是多态的,因为clone
是虚拟的。要了解更多此功能,请检查指针对象的类型,而不仅仅是指针的类型。您正在检查指针对象的类型指针,您没有检查指向对象的类型。顺便说一句,最好将克隆
函数声明为const
@cheers和hth.-Alf,为什么指针的类型是Base*
,因为重写函数将其返回类型声明为派生*
?如果它仍然返回Base*
,那么协变类型返回背后的全部原因?协变返回只对知道比最上面的基类更具体类型的代码有利。无论如何,声明类型是编译时的。对象类型可以更动态。谢谢!所以类型推断是静态绑定的,对吗?我想这就是我缺少的,我想bp->clone()
调用Derived::clone
,它返回一个Derived*
。但是现在我看到编译器不可能使用运行时类型推断,因为类型推断是在编译器时进行的…bp->clone()
在这种情况下确实调用了Derived::clone
,但如果bp
也是Base*
类型,则仍然必须将结果保存在Base*
变量中,以保持类型安全,因为编译器无法知道bp
是Derived
类型的指针。