append(int val)運行該函式時出現分段錯誤,并以多型方式呼叫,但我看不到 memalloc 錯誤的來源。我還是 C 的新手,經常遇到這個問題,但是當我自己修復它時,總是碰巧。任何指標?(沒有雙關語,或者是嗎:))
整陣列合.h
#ifndef INTEGERCOMBINATION_H
#define INTEGERCOMBINATION_H
using namespace std;
class IntegerCombination
{
public:
IntegerCombination();
void append(int Val);
virtual int combine() = 0;
protected:
int* _collection;
int _length;
};
#endif
整陣列合.cpp
#include "IntegerCombination.h"
IntegerCombination::IntegerCombination()
{
_length = 0;
}
void IntegerCombination::append(int val)
{
int newValPos = _length; // Stores current length as new position for new
// value
int* temp = _collection; //Stores current array
delete _collection; // Deletes current array
_length ; // Increases the length for the new array
_collection = new int[_length]; // Creates a new array with the new length
for(int i = 0; i < newValPos; i )
{
_collection[i] = temp[i]; // Allocates values from old array into new array
}
_collection[newValPos] = val; // Appends new value onto the end of the new array
}
主程式
#include "IntegerCombination.h"
#include "ProductCombination.h"
using namespace std;
int main()
{
ProductCombination objProd;
for(int i = 1; i <= 10; i )
{
objProd.append(i);
}
return 0;
}
注意:ProductCombination.h 和 ProductCombination.cpp 中的代碼并不完全相關,因為在 .cpp 檔案中,append(int val)只是將 append 呼叫委托給 IntegerCombination.h 中的基類
uj5u.com熱心網友回復:
對于初學者,建構式不會初始化資料成員 _collection
IntegerCombination::IntegerCombination()
{
_length = 0;
}
所以這個資料成員可以有一個不確定的值,并且使用帶有這樣一個指標的運算子 delete 會呼叫 undefined bejavior。
此外,當您嘗試分配陣列時,您需要使用運算子delete []而不是delete.
并且該類必須至少明確定義一個虛擬解構式。也可以將復制建構式和復制賦值運算子宣告為已洗掉,也可以明確定義它們。
該功能append有幾個錯誤。
如前所述,您需要delete []在此陳述句中使用運算子
delete _collection;
而不是運營商delete。
但必須在分配新陣列后呼叫此運算子。否則指標temp將具有無效值
int* temp = _collection; //Stores current array
delete [] _collection; // Deletes current array
也就是說,在將其元素復制到新分配的陣列后,您需要洗掉前一個陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/331735.html
上一篇:重新繪制jframe的更好方法
下一篇:在vs2019中創建服務
