gpt4 book ai didi

c++ - 在动态模板数组中使用 ADT 时程序崩溃

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

如果我们使用任何原始数据类型但不适用于 ADT,它将起作用即使所有复制构造函数“>>”“<<”“=”运算符都已重载并且还编写了复制构造函数你可以看到下面的每个代码谢谢提前

void main(){

Array <Item> c;//It will work if we use Any Permitive Data Type but not Working for ADT Even though all copy constructor / >> << operators are overloaded

Item obj(334,"Mango Juice",90,"Drinks",10);

c.insertAtStart(obj);
c.insertAtStart(obj);/////The program Crashes Here!!
c.insertAtStart(obj);


c.PrintArray();
cout<<endl;`


////while Array.h is given below
`
#ifndef H_ARRAY
#define H_ARRAY

#include<iostream>
using namespace std;

template<class T>
class Array
{
private:
T *a;
int size; // total size
int length_used; // used size
public:

Array():a(NULL),size(0),length_used(0){}

void insertAtStart( T val){

if(isEmpty()){
a=new T();
a[0]=val;

length_used++;
size++;
cout<<"Pehli condition"<<endl;
}

else{

if(size>length_used){
shiftRight();
a[0]=val;
length_used++;
cout<<"jab size bara ho length_used"<<endl;
}
else if(size==length_used){

cout<<"jab size or length_used braber ho jao 3rd condiot"<<endl;
resizeByOne();

shiftRight();
a[0]=val;
length_used++;

}

}
}




void insertAtEnd( T val){

if(isEmpty()){
a=new T;
a[0]=val;

length_used++;
size++;
}

else{

if(size>length_used){
a[length_used+1]=val;
length_used++;

}
else if(size==length_used){
resizeByOne();
a[length_used]=val;
length_used++;
}

}
}





void deleteFromStart(){

if(isEmpty()){
cout<<"Container is Empty"<<endl;
}

else{

a[0]=='\0';

shiftLeft();
size--;
length_used--;

}
}



void deleteFromEnd(){

if(isEmpty()){
cout<<"Container is Empty"<<endl;
}

else{

a[length_used]='\0';

length_used--;
size--;


}
}


void PrintArray(){

for(int i=0;i<size;i++)
cout<<a[i]<<endl;


}












////////////////////Helper functions///////////////////////

bool isEmpty(){
if(a=='\0')
return 1;
return 0;
}


void shiftRight(){

int tempIterator=size;
for(int i=tempIterator-1;i>=0;i--)
a[i]=a[i-1];
}


void shiftLeft(){

int tempIterator=length_used;
for(int i=0;i<size;i++)

a[i]=a[i+1];
a[0]=NULL;


}




void resizeByOne(){

T *temp=new T[size+1];

for(int i=0;i<length_used;i++)
temp[i]=a[i];

a=NULL;
delete []a;
a=temp;
size++;
}

};

#endif`

最佳答案

void shiftRight()
{

int tempIterator=size;
for(int i=tempIterator-1;i>=0;i--)
a[i]=a[i-1];
}

最后一次迭代导致 a[0] = a[-1],这可能会导致访问冲突,请尝试将 i>0 作为结束条件。这种情况下的访问冲突非常棘手。如果 a[-1] 处的内存是可访问的(例如,一些数据分配在那里),则不会发生异常/崩溃。异常以不确定的方式发生。

顺便说一句

a=NULL;
delete []a;

resizeByOne() 方法中。它不会导致任何异常(删除是安全的),但肯定会导致内存泄漏。

关于c++ - 在动态模板数组中使用 ADT 时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17191183/

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