如何引用基类的派生类?

how to refer to a base class's derived class?

本文关键字:派生 基类 何引用 引用      更新时间:2023-10-16
class Element { };
class Container {
vector<Element*> elements;
};

以上是原始代码。我被告知不要更改上述代码。现在我有

class IndexElement: public Element {
int b_index;
};
class Container* ctr;

现在我有了ctr->elements。但是Element没有成员b_index。有什么简单的方法可以将elements的归属从Element重定向到IndexElement?提前感谢!

您有一个选项:您知道向量中有IndexElement而不是Element,然后可以使用static_cast<IndexElement*>(elements[i]);。请注意,如果你没有IndexElement,那么这将彻底崩溃。

如果你可以修改b,那么你有另一个选择,通过使b成为虚拟的。如果你不知道,你可能有Elements和IndexElements,在这种情况下,使用dynamic_cast<IndexElement*>(elements[i]);并测试它,结果是否为nullptr。在这种情况下,b必须是虚拟的(因此是虚拟析构函数(。

(我假设我们在Container,所以直接访问其成员(

完整的试用(由于没有分配elements,将中断(与修改的元素:

#include <vector>
using namespace std;
class Element{
public:
virtual ~Element() {}
};
class Container{
public:
vector<Elements*>elements;
};
class IndexElement: public Element{
int index;
};
int main()
{
Container aa;
static_cast<IndexElement*>(aa.elements[0]);
dynamic_cast<IndexElement*>(aa.elements[0]);
return 0;
}

即使没有虚拟和RTTI(动态转换(,您仍然可以选择跟踪和检查创建的IndexElement实例,例如:

std::unordered_set<Element *> idxElemSet;
class IndexElement: public Element {
int b_index;
public:
IndexElement(int index) : b_index(index)
{ idxElemSet.insert(this); }
IndexElement(const IndexElement& other) : b_index(other.b_index)
{ idxElemSet.insert(this); }
// might also need the move constructor in case of c++11
~IndexElement()
{ idxElemSet.erase(this); }
};
int main()
{
Container c;
...
Element* e = c.elements[0];
if (idxElemSet.find(e) != idxElemSet.end()) {
IndexElement* ie = static_cast<IndexElement*>(e);
// do something with ie->b_index
}
return 0;
}

因此,您基本上可以保留创建的所有实例的地址集,在检查特定实例时,只需检查当前对象地址是否在该集中。

idxElemSetIndexElement内部也可以是静态的,类本身可能只提供静态转换功能,在内部进行检查和转换等。