智能指针和多态 [英] Smart pointers and polymorphism

查看:383
本文介绍了智能指针和多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了引用计数指针(在示例中称为 SP ),我有多态性的问题,我认为我不应该有。

I implemented reference counting pointers (called SP in the example) and I'm having problems with polymorphism which I think I shouldn't have.

在以下代码中:

    SP<BaseClass> foo()
    {   
        // Some logic...
        SP<DerivedClass> retPtr = new DerivedClass();
        return retPtr;
    }

DerivedClass BaseClass 。对于正常的指针,这应该是有效的,但是对于智能指针,它表示不能从'SP< T>'转换到const SP< T>&认为它指的是智能指针的复制构造函数。

DerivedClass inherits from BaseClass. With normal pointers this should have worked, but with the smart pointers it says "cannot convert from 'SP<T>' to 'const SP<T>&" and I think it refers to the copy constructor of the smart pointer.

如何通过引用计数指针允许这种多态性?
我会喜欢的代码示例导致显然我做错了这里,如果我有这个问题。

How do I allow this kind of polymorphism with reference counting pointer? I'd appreciate code samples cause obviously im doing something wrong here if I'm having this problem.

PS:请不要告诉我使用带有智能指针的标准库,因为这在目前是不可能的。

PS: Please don't tell me to use standard library with smart pointers because that's impossible at this moment.

推荐答案

相当明显:

SP<DerivedClass> retPtr = new DerivedClass();

应为:

SP<BaseClass> retPtr = new DerivedClass();

这篇关于智能指针和多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆