我正在尝试将对 Base 对象的引用向量转换为对 Derived 对象的引用向量。一切编译正常,但我收到此错误:运行时错误时间:0 内存:3412 信号:6
这是我的代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct B {
B(int i) { b = i; }
virtual ~B() {}
int b;
};
struct D: public B {
D(int i): B(i) {}
};
typedef vector<reference_wrapper<B>> refB;
typedef vector<reference_wrapper<D>> refD;
void dynamicCast(refB &b, refD &d)
{
for(const auto& bb: b)
{
d.push_back(dynamic_cast<D&> (bb.get()));
}
}
int main() {
vector<B*> numbers;
refB refNumbers;
refD dNumbers;
for(int i = 0; i < 10; i++)
{
numbers.push_back(new B(2*i));
refNumbers.push_back(*numbers[i]);
}
dynamicCast(refNumbers, dNumbers);
return 0;
}
dynamicCast() 函数有什么问题?
编辑:@John Zwinck 回答有帮助,但是当我尝试在我的代码中执行此操作时,我得到了编译错误:
不能 dynamic_cast '(& obj)->std::reference_wrapper<_Tp>::get()' (类型为 'class MEPObject')键入 'class MEPGene&' (目标不是指针或完整类型的引用)genes.push_back (dynamic_cast (obj.get()));
class MEPObject;
class MEPGene;
typedef std::vector<std::reference_wrapper<MEPObject>> MEPObjects;
typedef std::vector<std::reference_wrapper<MEPGene>> MEPGenes;
void dynamicCast(MEPObjects &objects, MEPGenes &genes)
{
for(const auto &obj: objects)
{
genes.push_back(dynamic_cast<MEPGene&> (obj.get()));
}
}
^