我的以下代码有问题。我有一个无法修改的基类和派生类。我有一个 vector ,其中存储了一些指向基类的指针。
现在,当我遍历 vector 时,应根据变量的类型调用正确的void函数。
#include <iostream>
#include <vector>
using namespace std;
//base and a can't be modified, because they are in a library
class base
{
virtual ~base(){};
};
class a : public base
{
virtual ~a(){};
};
void Funktion(base* variable)
{
cout << "base" << endl;
}
void Funktion(a* variable)
{
cout << "a" << endl;
}
int main()
{
vector<base*> list;
list.push_back(new a());
list.push_back(new base());
for each (base* var in list)
Funktion(var);
}
在此示例中,它应输出:
a
base
但是它输出:
base
base
有人可以帮我解决这个问题吗?
问候斯蒂芬
编辑:插入虚拟析构函数
最佳答案
一种解决方案是使用虚拟功能。您还可以使用std::unique_ptr
避免内存泄漏,即:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class base{
public:
base() { }
virtual ~base() { }
virtual void function() { std::cout << "base\n"; }
};
class a : public base
{
public:
a() { }
~a() { }
virtual void function() { std::cout << "a\n"; }
};
int main()
{
vector<std::unique_ptr<base>> list;
list.push_back(std::unique_ptr<base>(new a()));
list.push_back(std::unique_ptr<base>(new base()));
for (const auto& e : list)
{
e->function();
}
}
另一种方法是为派生对象尝试
dynamic_cast
。 a* ptr = dynamic_cast<a*>(e.get());
if (ptr)
funktion(ptr);
else
funktion(e.get());