【发布时间】:2020-07-23 01:20:29
【问题描述】:
我正在尝试重载 = 运算符以复制并最终交换两个双端队列?
但是我得到了
free(): invalid pointer
Aborted (core dumped)
while 循环退出时出错。当 tempDeque.display(); 函数调用被注释掉时,一切运行正常。
这里是运算符重载的代码块:
class Resizeable_deque{
private:
T* array;
int front;
int back;
int deque_size;
int capacity;
int initial_capacity;
public:
// Resizeable_deque();
//accessors
Resizeable_deque(int n=10) //done constructor
{
if (n==10)
{
array = new T[10];
capacity = 10;
initial_capacity = 10;
front = -1;
back = 0;
deque_size = 0;
// cout << "Capacity = " << capacity << endl;
// cout << "OK!";
}
else if (n<=10)
{
array = new T [n];
capacity = n;
initial_capacity = n;
front = -1;
back = 0;
deque_size = 0;
// cout << "Capacity = " << capacity << endl;
// cout << "OK!!";
}
}
~Resizeable_deque(); //done destructor
//accessors
T* getArray() const;
T getFront() const; // done get front element
T getBack() const; //done get last element
int size() const; //done get the size of the queue
int getCapacity() const; //done get the current capacity of queue
int getInitialCapacity() const;
//data member setters
// void setArray(T* newArray);
// void setfront(int newFront);
// void setBack (int newBack);
// void setSize (int newSize);
// void setCapacity (int newCapacity);
// void setInitialCapacity(int newInitialCapacity);
//state check functions
bool full() const;
bool empty() const; //done check if empty
T display() const;
//mutators
void push_front (const T e);
void push_back (const T e);
void pop_front();
void pop_back();
void pop_front_back();
void resizeDeque(float resizefactor, int newsize);
void swap(Resizeable_deque tempDeque);
Resizeable_deque operator=(Resizeable_deque b)
{
cout <<"B:";
b.display();
cout << "Back: " << b.getBack() << endl;
int bSize = b.size();
Resizeable_deque<string> tempDeque(b.getCapacity());
while (!b.empty())
{
tempDeque.push_back(b.getFront());
// b.display();
b.pop_front();
cout<< "popped!" << endl;
tempDeque.display();
cout << "back is: " << b.getFront() << endl;
cout << endl;
cout << endl;
cout << endl;
}
//end of loop call swap
};
void clear();
};
【问题讨论】:
-
问题可能出在算子的原型上。你能把它和你的类定义一起粘贴吗?
-
我怀疑您在未显示的代码中的某处有未定义的行为。请编辑您的问题以提供minimal reproducible example。
标签: c++ class pointers overloading free