如何引用基类的派生类?
how to refer to a base class's derived class?
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成为虚拟的。如果你不知道,你可能有Element
s和IndexElement
s,在这种情况下,使用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;
}
因此,您基本上可以保留创建的所有实例的地址集,在检查特定实例时,只需检查当前对象地址是否在该集中。
idxElemSet
在IndexElement
内部也可以是静态的,类本身可能只提供静态转换功能,在内部进行检查和转换等。
相关文章:
- 如何通过派生类函数更改基类中的向量
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 在派生类中使用基类的私有成员变量的最佳方法
- 基类和派生类的多态赋值运算符
- 如何在从抽象基派生的类中实现相同的方法?
- 基类的填充将被复制到派生类中
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 指向基类派生类的 std::unique_ptr 的指针
- 为什么基类数据在派生类数据之前初始化
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 如何将基类替换为派生基类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 解析公用派生基类模板中的函数模板名称时出错"Not declared in this scope"