C++转换运算符重载问题
我有自己的 SmartPointer 类。
在某些情况下,SmartPtr 包含从基类继承的类,并且我想将 SmartPtr
我试图重载 SmartPtr Conversion 运算符来执行此操作。
它对类本身工作得很好,例如:
template<class newType>
operator SmartPtr<newType>() const
{
return SmartPtr<newType>((SmartPtr<newType>*)this);
}
但不适用于指向类的指针,我已经尝试了以下操作,但它永远不会被调用并出现以下错误:
template<class newType>
operator SmartPtr<newType>*() const
{
return static_cast<SmartPtr<newType>*>(this);
}
获取错误的简单代码:
SmartPtr<ClassX> test(pClassX);
SmartPtr<BaseClassOfClassX>* ob = &test;
ERROR:
cannot convert from 'SmartPtr<T> *' to 'SmartPtr<T> *'
有人看到什么问题了吗我的第二个转换超载? 谢谢
I have my own SmartPointer class.
There are cases where SmartPtr contain a class that inherite from a Base class, and I would like to convert SmartPtr<ClassX> into SmartPtr<BaseClassOfClassX>;
I am trying to overload the SmartPtr Conversion operator to do this.
It work fine for the Class themself, such as:
template<class newType>
operator SmartPtr<newType>() const
{
return SmartPtr<newType>((SmartPtr<newType>*)this);
}
but not for pointer to the Class, I have tried the following, and it never gets call and get the following error:
template<class newType>
operator SmartPtr<newType>*() const
{
return static_cast<SmartPtr<newType>*>(this);
}
Simple code to get the error:
SmartPtr<ClassX> test(pClassX);
SmartPtr<BaseClassOfClassX>* ob = &test;
ERROR:
cannot convert from 'SmartPtr<T> *' to 'SmartPtr<T> *'
Does anyone see what is wrong with my second conversion overload?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 C++ 标准:“运算符函数应该是非静态成员函数,或者是非成员函数,并且至少有一个
类型为类、类的引用、枚举或枚举的引用的参数。”
由于
&test
的类型不是类,也不是任何可隐式转换的类型对于类,您不能直接重载指针上的类型转换,具体取决于您需要指向智能指针的指针,也许您确实想使用更常见的引用。From the C++ standard: "An operator function shall either be a non-static member function or be a non-member function and have at least one
parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration."
As the type of
&test
is not a class nor anything implicitly convertible to a class, you cannot overload the typecasts on the pointer directly. Depending on why you need pointers to your smart pointers, maybe you really want to employ references which is much more common.