Я создаю собственный класс Vector для динамических c массивов. Для моего перегруженного оператора [] у меня есть неконстантная версия и константная версия. Я использую эту перегрузку оператора для вызова метода расширения, который увеличивает размер моего динамического массива c, если index [] больше емкости массива, и если нет, возвращает объект по индексу. Нет ничего плохого в моих данных входного файла, так как я выполнил эту операцию, используя массивы объектов, но сейчас я пытаюсь сделать это с помощью этого пользовательского векторного класса, и он не позволит мне скомпилироваться из-за error: passing 'const Vector<Result>' as 'this' argument discards qualifiers [-fpermissive]|.
Что может быть не так ? Ошибка в строке 'this->expand'
под моим const T& Vector<T>::operator[](int index) const
.
. Любые отзывы о том, правильный ли мой синтаксис, были бы полезны. Кроме того, в классе, в котором я создал вектор, я объявляю его частной переменной в .h следующим образом: Vector<Result> results;
и помещаю в него данные, как в моем. cpp следующим образом:
void Registration::readFile(istream &input){
long studentid1;
unsigned semester1;
input >> studentid1 >> semester1 >> count;
SetStudentID(studentid1);
SetSemester(semester1);
for(unsigned i = 0; i < count; i++){
input >> results[i];
}
}
void Registration::writeFile(ostream & os) const{
os << "Student ID: " << GetStudentID() << '\n'
<< "Semester: " << GetSemester() << '\n';
for(unsigned i = 0; i < count; i++)
os << results[i] << '\n';
}
Это будет правильный путь? Вот мой vector.h:
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
class Vector
{
public:
Vector(int size = 10);
~Vector();
void initialize(int from);
void expand();
T& operator[](const int index);
const T& operator[](const int index) const;
private:
T **data;
int capacity;
int nrofel;
};
template <class T>
Vector<T>::Vector(int size){
this->capacity = size;
this->nrofel = 0;
this->data = new T*[this->capacity];
initialize(this->nrofel);
}
template <class T>
T& Vector<T>::operator[](int index){
if(index >= capacity){
this->expand();
}
return *this->data[index];
}
template <class T>
const T& Vector<T>::operator[](int index) const{
if(index >= capacity){
this->expand();
}
return *this->data[index];
}
template <class T>
void Vector<T>::initialize(int from){
for(size_t i = from; i < capacity; i++){
this->data[i] = nullptr;
}
}
template <class T>
Vector<T>::~Vector(){
for(size_t i = 0; i < capacity; i++){
delete this->data[i];
}
delete[]this->data;
}
template <class T>
void Vector<T>::expand(){
this->capacity *= 2;
T** tempData = new T*[this->capacity];
for(size_t i = 0; i < this->nrofel; i++){
tempData[i] = this->data[i];
}
delete[] data;
this->data = tempData;
initialize(this->nrofel);
}
#endif // VECTOR_H
Я прошу прощения за перегрузку информации, но мне нужно, чтобы это скоро заработало. Если кто-нибудь может оказать мне какую-то помощь, это будет с благодарностью.