找出父型向量元素的子类型

Find out the child-type of an element of parent-type vector

本文关键字:类型 元素 向量 父型      更新时间:2023-10-16

我有一个抽象的父班,名为"表单"和一些子类,例如"圆"answers"星"。如果我将这些子类的多个实例保存在父型向量中,我有什么办法可以找到单个元素的子类型?

//类

class Form {
public:
Form();
virtual ~Form() = default;
virtual  void Draw(CDC* pDC)abstract;
};
class Circle :public Form {
public:
Circle();
~Circle();
void Draw(CDC* pDC) override;
CPoint GetUpperLeft();
CPoint GetLowerRight();

private:
CPoint m_upperLeft;
CPoint m_lowerRight;
};

//main

int main(){
std::vector<Form> m_forms;
m_forms.pushback(Circle());
m_forms.at(0);//??
}

@john刚才建议,您可以使用typeid()

一些我的代码汇总在一起,证明原则是...

#include <iostream>
#include <typeinfo>
struct Base
{
    virtual ~Base() {}
};
struct Derived : public Base
{
    virtual ~Derived() {}
};
struct Circle : public Base
{
    virtual ~Circle() {}
};

int main()
{
    Derived d;
    Circle c;
    Base *b1 = &d; 
    Base *b2 = &c;
    std::cout << typeid(*b1).name() << std::endl;
    std::cout << typeid(*b2).name() << std::endl;

}

也许不是理想的方式,而是一个简单的方式,通过向父返回true的父函数中的简单方式&amp;在孩子中覆盖它,因此返回false

class Form { 
public:
Form();
virtual ~Form() = default;
virtual  void Draw(CDC* pDC)abstract;
virtual bool isParent(){ return 1;}
};
class Circle :public Form {
public:
Circle();
~Circle();
void Draw(CDC* pDC) override;
CPoint GetUpperLeft();
CPoint GetLowerRight();
 bool isParent(){ return 0;}
private:
CPoint m_upperLeft;
CPoint m_lowerRight;
};

其次注意到,如果要在推到向量时创建元素,则应使用:

m_forms.emplace_back(new Circle());

避免制作额外的副本

补充,您要声明对象向量的方式

vector<Form> m_forms;
stores values, not references. 
vector<Form*> m_forms
Or, better yet:
vector< std::shared_ptr<Form> > m_forms