答:总之用虚函数!因此,实际上不要将其用作良好的设计,但出于学习目的,请阅读!
首先我想说我正在使用 c++ 和 Qt
我有一个形状指针向量(基类)
编辑: doSomething() 不是基类的成员,而是派生类的成员。这就是为什么我使用dynamic_cast 将 Shape* 获取到 Derived* 以便我可以访问它。我这样做实际上只是出于好奇,也为了其他人了解 c++ 的类型系统
#include <vector>
using namespace std;
vector<Shape *> vec;
我推回一些形状的派生类
vec.push_back(new Square());
vec.push_back(new Circle());
好的,然后我得到一个迭代器到开头
vector<Shape *>::iterator tmp = vec.begin();
这里我想迭代向量
for(;tmp != vec.end(); ++tmp)
{
if(typeid(**tmp).name() == typeid(Square).name())
{
Square * sptr = dynamic_cast<Square *>(*tmp);
sptr->doSomething();
}
else if(typeid(**tmp).name() == typeid(Circle).name())
{
Circle * cptr = dynamic_cast<Circle *>(*tmp);
cptr->doSomething();
}
}
然而,两者都会产生 Square 输出;不是第二个圆圈。我尝试比较 typeid 的内存位置
Like so:
&typeid(**tmp) == &typeid(Square)
对于圆也是如此,但 tmp 总是会在上面的情况下产生正方形,并且当之后立即与圆运行时...动态转换是否对整个矢量进行了一些操作,我只是错过了 typeid() 工作原理的一些东西?
编辑:
这是答案,感谢 user4581301 (我也添加了一些东西!):
#include <iostream>
#include <vector>
#include <typeinfo>
struct Shape
{
virtual ~Shape(){} //Something here must be virtual or pure virtual!
};
struct Circle: Shape
{
void doSomething(){std::cout << "Circle" << std::endl;}
};
struct Square: Shape
{
void doSomething(){std::cout << "Square" << std::endl;}
};
int main()
{
std::vector<Shape *> vec;
vec.push_back(new Square());
vec.push_back(new Circle());
std::vector<Shape *>::iterator tmp = vec.begin();
for(;tmp != vec.end(); ++tmp)
{
if(&typeid(**tmp) == &typeid(Square))
{
Square * sptr = dynamic_cast<Square *>(*tmp);
sptr->doSomething();
}
else if(&typeid(**tmp) == &typeid(Circle))
{
Circle * cptr = dynamic_cast<Circle *>(*tmp);
cptr->doSomething();
}
}
}