找出父型向量元素的子类型
Find out the child-type of an element of parent-type vector
我有一个抽象的父班,名为"表单"和一些子类,例如"圆"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
相关文章:
- 在C++中,如何通过几种类型从元组中选择多个元素
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 在 C++ 中输出枚举类类型的向量元素
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 如何使用模板根据类型将元素添加到各种容器中
- C++ 未初始化的本地(非全局)int 数组中的元素类型到底是什么?
- OpenCV C++:当垫子类型未知时无法访问垫子元素?
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- C++:是否可以编写一个函数,将不同类型的元素附加到变体数组中?
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 我无法在用forward_as_tuple创建的元组中按类型访问元素
- 如何告诉自动推断向量<bool>元素的非引用类型
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 如何为基类通用类型创建向量以使用具体类型元素
- 按索引将类类型元素从一个向量复制到另一个 c++
- 如何实现数据结构,就像C 中的数组一样支持不同的类型元素
- 如何在构造具有不同类型元素的向量副本时显式转换
- 处理特定类型元素的任何容器的非模板函数
- *类型元素容器的qt排序
- 如何将两个双数据类型元素转换为一个Point数据类型