gpt4 book ai didi

c++ - new with inheritance 的不当使用?

转载 作者:行者123 更新时间:2023-11-30 05:34:44 28 4
gpt4 key购买 nike

我正在尝试找出崩溃的原因,并将其归结为以下示例:

class Base
{
public:
virtual unsigned int GetNum () = 0;
};

class Derived : public Base
{
int data; // <--- commmenting this out removes the crash

public:
Derived() {}
virtual unsigned int GetNum() { return 1; }
};

void func() {

Base** ppBases;

unsigned int xLen = 3;
unsigned int yLen = 4;

ppBases = new Base*[xLen];
for(unsigned int x = 0; x < xLen; ++x) {
ppBases[x] = new Derived[yLen];
for(unsigned int y = 0; y < yLen; ++y) {
Base* curBase = dynamic_cast<Base*>(&(ppBases[x][y]));
Derived* curDerived = dynamic_cast<Derived*>(&(ppBases[x][y])); // <--- crashes with a null dereference
unsigned int result = curBase->GetNum();
result = result;
}
}
}

我猜 Derived 实际上并没有被分配正确的大小。将 ppBases 更改为三重指针(像这样)使一切正常:

void func() {

Base*** ppBases;

unsigned int xLen = 3;
unsigned int yLen = 4;

ppBases = new Base**[xLen];
for(unsigned int x = 0; x < xLen; ++x) {
ppBases[x] = new Base*[yLen];
for(unsigned int y = 0; y < yLen; ++y) {
ppBases[x][y] = new Derived();
Base* curBase = dynamic_cast<Base*>(ppBases[x][y]);
Derived* curDerived = dynamic_cast<Derived*>(ppBases[x][y]);
unsigned int result = curBase->GetNum();
result = result;
}
}
}

虽然我不明白为什么。

谢谢

最佳答案

问题出在这一行:

 ppBases[x] = new Derived[yLen];

您正在将一组 Derived 对象分配给 Base * 指针。因此,当您编写 ppBases[x][y] 时,编译器会使用指针的类型,即 Base *,并进行适当的索引。所以 ppBases[x][1] 不引用分配数组中的第二个 Derived 对象。

关于c++ - new with inheritance 的不当使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113371/

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