[英]Transform std:vector<reference_wrapper<Base>> to std:vector<reference_wrapper<Derived>> Runtime error time: 0 memory: 3412 signal:6
I am trying to convert vector of references to Base objects to vector of references to Derived objects. 我正在尝试将对基础对象的引用向量转换为对派生对象的引用向量。 Everything is compiling fine, but i got this error: Runtime error time: 0 memory: 3412 signal:6
一切都编译良好,但我收到此错误:运行时错误时间:0内存:3412 signal:6
This is my code: 这是我的代码:
#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;
}
What is wrong with dynamicCast() function? dynamicCast()函数怎么了?
EDIT: @John Zwinck answer helped, but when i try to do this in my code i got compilation error: 编辑:@John Zwinck答案有所帮助,但是当我尝试在我的代码中执行此操作时,出现编译错误:
cannot dynamic_cast '(& obj)->std::reference_wrapper<_Tp>::get()' (of type 'class MEPObject') to type 'class MEPGene&' (target is not pointer or reference to complete type) genes.push_back(dynamic_cast (obj.get()));
无法将'(&obj)-> std :: reference_wrapper <_Tp> :: get()'(类型为'MEPObject'类型)'动态转换为'类MEPGene&'(目标不是指针或对完整类型的引用)基因。 (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()));
}
}
^
Nothing is wrong with dynamicCast()
. dynamicCast()
。 The problem is here: 问题在这里:
numbers.push_back(new B(2*i));
You only ever construct instances of B
which is the base class. 您只能构造作为基类的
B
实例。 You can't possibly cast them to D
which is the derived class. 您不可能将它们
D
为派生类D
Perhaps you meant to construct derived instances and store them in your vector of references to base. 也许您打算构造派生实例并将其存储在对base的引用向量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.