我有这个问题:
// the classes
class cBase {};
class cDerived : public cBase {};
class cBaseArray
{
// the array of pointers to cBase
cBase** array;
// overloaded operator that returns an element of the array
cBase*& operator[](unsigned index)
{
// much more complicated, but simplified for example
return array[index];
}
};
class cDerivedArray : public cBaseArray
{
// overloaded operator that returns a converted element of the array
cDerived*& operator[](unsigned index)
{
// conversion required, but don't know how
return static_cast<???>(cBaseArray::operator[](index));
}
};
那么如何将
cBase
的 operator[]
返回的指向 cBaseArray
的指针的引用转换为 cDerived
的 operator[]
返回的指向 cDerivedArray
的指针的引用? 最佳答案
要返回引用,它必须是对特定对象的引用。 cDerived*&
必须引用实际的 cDerived*
(即它必须是左值)。由于您没有任何 cDerived*
,因此您无法返回对一个的引用。
如果你不需要支持语法 myDerived[4] = anotherPtr;
那么你可以只返回 cDerived *
,这没问题。如果您必须返回引用,那么除了返回 cBase *&
之外别无选择,并且如果调用方想要访问无法通过 dynamic_cast<>
访问的内容,则要求调用者对结果执行 cBase *
。
可以设计一个特殊的对象,cDerived::operator[]
返回并保存对 cBase *
的引用;并且该对象定义了 operator=
,它可以采用 cDerived *
,并且该对象具有到 cDerived *
的转换运算符。这增加了复杂性,我建议不要这样做,除非您对我上一段的解决方案真的不满意
注意。要获得多态行为,您必须使 cBase
具有多态性,即至少包含一个虚函数 - 我假设您打算这样做,但为了简洁起见将其省略。
关于C++ 将基指针的引用转换为派生指针的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24117631/