gpt4 book ai didi

c++ - 转换标准 :vector> to std:vector> Runtime error time: 0 memory: 3412 signal:6

转载 作者:行者123 更新时间:2023-11-28 02:02:49 25 4
gpt4 key购买 nike

我正在尝试将对 Base 对象的引用 vector 转换为对 Derived 对象的引用 vector 。一切编译正常,但我收到此错误:运行时错误时间: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 的回答有帮助,但是当我尝试在我的代码中执行此操作时,我遇到了编译错误:

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()));

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()));
}
}
^

最佳答案

dynamicCast() 没有问题。问题出在这里:

    numbers.push_back(new B(2*i));

您只能构造 B 的实例,它是基类。您不可能将它们转换为派生类 D

也许您打算构造派生实例并将它们存储在您对 base 的引用 vector 中。

关于c++ - 转换标准 :vector<reference_wrapper<Base>> to std:vector<reference_wrapper<Derived>> Runtime error time: 0 memory: 3412 signal:6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38730846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com