英文:
c++ 14 (VS 2015) shared_ptr with protected inheritance - no suitable user defined conversion
问题
我在使用受保护继承时,使用共享指针出现了奇怪的编译错误。下面这段简单的代码无法编译,出现错误 "没有合适的用户定义转换",但在使用公共继承时可以正常工作。不确定原因,有人能解释一下吗?
class ioptionpricer
{
public:
virtual std::shared_ptr<ioptionpricer> clone() const = 0;
virtual void doSomething() const = 0;
virtual ~ioptionpricer() = default;
};
class optionpricer : protected ioptionpricer
{
public:
std::shared_ptr<ioptionpricer> clone() const
{
return std::make_shared<optionpricer>(*this);
}
};
英文:
I'm getting a strange compilation error when using shared pointer with protected inheritance. The below simple code doesn't compile and gives error "no suitable user defined conversion" but it works with public inheritance. Not sure why, could anyone please explain?
class ioptionpricer
{
public:
virtual std::shared_ptr<ioptionpricer> clone() const = 0;
virtual void doSomething() const = 0;
virtual ~ioptionpricer() = default;
};
class optionpricer : protected ioptionpricer
{
public:
std::shared_ptr<ioptionpricer> clone() const
{
return std::make_shared<optionpricer>(*this);
}
};
答案1
得分: 1
当继承是私有的(或受保护的),则在类外部(或受保护继承的派生类)无法将 derived*
强制转换为 base*
。
在将 shared_ptr<derived>
转换为 shared_ptr<base>
时,derived*
到 base*
的转换发生在 shared_ptr<T>
模板的实现中。因此,使用私有/受保护继承不可行,除非将 shared_ptr
声明为友元。
无论如何,在这些情况下只需使用 public
继承,将其设为私有或受保护在这种情况下是没有意义的。
英文:
When the inheritance is private (or protected) then one cannot cast derived*
to base*
outside of the class (or derived classes for protected inheritance).
In case of conversion from shared_ptr<derived>
to shared_ptr<base>
, the conversion from derived*
to base*
happens somewhere in implementation of the template shared_ptr<T>
. So, with private/protected inheritance it won't fly. Unless you declare shared_ptr
to be a friend.
Either way just use public
inheritance in these situations, it is pointless to make it private or protected in such situations.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论