简体   繁体   English

函数内部的抽象类对象指针调用的C ++ abort()

[英]C++ abort() on abstract class object pointer call inside a function

I've got an abstract class pendulum with pure virtual function period() and two descendants(math and spring) implementing function period(). 我有一个抽象类的钟摆,它带有纯虚函数period()和两个后代(数学和弹簧),实现函数period()。

I've got a pendulum **pendArray = new pendulum*[n]. 我有一个摆锤** pendArray =新摆锤* [n]。 I fill the array with math and spring class object pointers and pass the array to the findMaxPeriod(pendulum **a) function: 我用数学和spring类对象指针填充数组,并将数组传递给findMaxPeriod(pendulum ** a)函数:

void findMaxPeriod(pendulum **a) 
{
    pendulum *maxPend = new math();
    double maxPeriod = 0;
    double period1;
    for (int i = 0; i < n; i++)
    {
        pendulum *pend = a[i];
        period1 = pend->period();
        if (period1 > maxPeriod)
        {
            maxPend = a[i];
        }
    }
    cout << "max period pendulum is " << maxPend << ". It's period is " << maxPend->period();
}

It crashes on the 它崩溃了

period1 = pend->period();

with "debug error! abort() has been called" 与“调试错误!已调用abort()”

What am I doing wrong? 我究竟做错了什么? Here is all my code: https://hello-site.ru/share/Abort-called-problem/ Thanks in advance. 这是我所有的代码: https : //hello-site.ru/share/Abort-drawn-problem/预先感谢。

The problem is here: 问题在这里:

math pendM;
cin >> pendM;
pendArray[i] = &pendM;

In the third line, you've place a pointer-to- pendM into your array, but pendM gets destroyed immediately after that line, when it goes out of scope. 在第三行中,您已将指向pendM的指针pendM到数组中,但是当pendM超出范围时,它将在该行之后立即被销毁。 If you want to keep it around (and thus avoid a dangling pointer in your pendArray ) you'll need to allocate it from the heap instead of on the stack. 如果要保留它(从而避免在pendArray悬空的指针),则需要从堆而不是堆栈中分配它。

Same thing goes for pendS in the next block below that. 下一个方框中的pendS也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM