我尝试执行简单的向量c ++实现,并且它可以与简单的typename(或类,相同的东西)一起工作,但是对于typename *(double *或Test *),我有一个错误,为什么?我尝试将表示法更改为->,这应该可以正常工作,但事实并非如此!我误会了什么?我尝试使用VS2017进行调试,但是我没有发现什么地方出了问题,operator []返回* Test,并且对元素使用了->。
Source.cpp
#include <iostream>
#include "Vector.h"
using namespace std;
class Test
{
public:
double a = 1;
Test(){}
};
int main()
{
Vector<Test*> Vec2(10);
{
for (int i = 0; i < 10; i++)
Vec2[i]->a = i;
}
for (int i = 0; i < 10; i++)
cout << "Vec2[" << i << "] = " << Vec2[i]->a << endl;
return 0;
}
Vector.h
#include <cstdlib>
#include <cassert>
template <typename T>
class Vector
{
public:
T *arr = nullptr;
size_t _size = 0;
size_t _capacity = 4;
Vector() {
arr = new T[_capacity];
}
Vector(size_t size) {
_capacity = size << 2;
arr = new T[_capacity];
_size = size;
}
~Vector() {
delete[] arr;
}
size_t size() {
return _size;
}
size_t capacity() {
return _capacity;
}
void clear() {
_size = 0;
}
T& operator[](size_t idx) { return arr[idx]; }
const T& operator[](size_t idx) const { return arr[idx]; }
void reallocate()
{
T *arr_n = new T[_capacity];
for (int i = 0; i < _size; i++)
arr_n[i] = arr[i];
delete[] arr;
arr = arr_n;
}
Vector& operator=(const Vector& B) {
reallocate(B.capacity());
_size = B.size();
for (size_t j = 0; j < _size; ++j) {
arr[j] = B->arr[j];
}
return *this;
}
void push_back(T input)
{
if (_size == _capacity) {
_capacity <<= 2;
reallocate();
}
arr[_size] = input;
++_size;
}
};