C++ 为什么这会让我违反访问权限?(C+;+;)
我正在为我的data structures类构建一个vector类,我不明白为什么会抛出异常。下面是完整的Vector.h文件:C++ 为什么这会让我违反访问权限?(C+;+;),c++,vector,dynamic-memory-allocation,C++,Vector,Dynamic Memory Allocation,我正在为我的data structures类构建一个vector类,我不明白为什么会抛出异常。下面是完整的Vector.h文件: #include <iostream> using namespace std; template <class T> class Vector { private: // not yet implemented Vector(const Vector& v); Vector& operator=(const
#include <iostream>
using namespace std;
template <class T>
class Vector {
private:
// not yet implemented
Vector(const Vector& v);
Vector& operator=(const Vector& v);
T * Tarray;
int arraySize;
int currentSize;
public:
Vector() {
arraySize = 2;
currentSize = 0;
Tarray = new T[arraySize];
};
~Vector() {
delete[] Tarray;
};
void push_back(const T &e) {
++currentSize;
if (currentSize > arraySize) {
arraySize *= 4;
T * temp = new T[arraySize];
for (int i = 0; i < currentSize; i++) {
temp[i] = Tarray[i];
}
delete[] Tarray;
Tarray = new T[arraySize];
for (int j = 0; j < currentSize; j++) {
Tarray[j] = temp[j];
}
delete[] temp;
Tarray[currentSize - 1] = e;
}
else {
Tarray[currentSize - 1] = e;
}
};
void print() {
for (int i = 0; i < currentSize; i++) {
cout << Tarray[i] << " ";
}
};
int getCurrentSize() {
return currentSize;
};
int getArraySize() {
return arraySize;
};
// Not yet implemented
void pop_back();
int size() const;
T& operator[](int n);
};
#包括
使用名称空间std;
模板
类向量{
私人:
//尚未实施
向量(常数向量&v);
向量和运算符=(常量向量和v);
T*Tarray;
内部阵列化;
int-currentSize;
公众:
向量(){
arraySize=2;
currentSize=0;
Tarray=新的T[阵列化];
};
~Vector(){
删除[]Tarray;
};
无效推回(施工T&e){
++电流大小;
如果(当前大小>阵列大小){
阵列化*=4;
T*temp=新的T[arraySize];
对于(int i=0;i cout我将重写push_back
,如下所示:
void push_back(const T &e) {
if (currentSize+1 > arraySize) {
arraySize *= 4;
T * temp = new T[arraySize];
for (int i = 0; i < currentSize; i++) {
temp[i] = Tarray[i];
}
delete[] Tarray;
Tarray = temp;
}
Tarray[currentSize] = e;
++currentSize;
};
void push_back(施工测试与评估){
如果(currentSize+1>阵列化){
阵列化*=4;
T*temp=新的T[arraySize];
对于(int i=0;i
变化如下:
- 在复制内容之前不要更新
currentSize
(因此不会超出Tarray
的范围)
- 不要分配和复制两次。删除后只需将
Tarray
分配给temp
- 仅在一个位置将元素粘贴到
Tarray
- 之后更新
currentSize
,以避免必须执行-1
(如果,则在第一个中需要一个+1
)
我将重写向后推
,如下所示:
void push_back(const T &e) {
if (currentSize+1 > arraySize) {
arraySize *= 4;
T * temp = new T[arraySize];
for (int i = 0; i < currentSize; i++) {
temp[i] = Tarray[i];
}
delete[] Tarray;
Tarray = temp;
}
Tarray[currentSize] = e;
++currentSize;
};
void push_back(施工测试与评估){
如果(currentSize+1>阵列化){
阵列化*=4;
T*temp=新的T[arraySize];
对于(int i=0;i
变化如下:
- 在复制内容之前不要更新
currentSize
(因此不会超出Tarray
的范围)
- 不要分配和复制两次。删除后只需将
Tarray
分配给temp
- 仅在一个位置将元素粘贴到
Tarray
- 之后更新
currentSize
,以避免必须执行-1
(如果,则在第一个中需要一个+1
)
如果有一个可以编译和运行的完整示例,这将非常有帮助。您确实可以跳出TArray
,因为在迭代之前更新currentSize
。for(int i=0;i
你不是刚增加了currentSize
吗?哦,好的一点,需要是currentSize-1
。有一些完整的示例可以编译和运行,这将非常有帮助。你确实要超出TArray
,因为你在迭代它之前更新了currentSize
。(inti=0;i
你不是刚增加了currentSize
?哦,好的,需要是currentSize-1
。