【发布时间】:2020-08-15 14:51:07
【问题描述】:
我对当前的项目有点卡住了。我在一个类中创建了一个方法,该方法从文件中读取输入,并将其发送到一个 Result 对象(类)数组。当我这样做时,它使用结果类输入流方法以我想要的方式读取输入。现在我有一个名为 Vector 的自定义类模板,用于动态数组,其中 Result 是我的 Vector。我需要如何更改输入语法以及 Vector 中需要哪种方法?我用于读取结果对象数组的方法是这样的:
void Registration::SetSemester(unsigned semester1){
semester = semester1;
}
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];
}
}
这是我的 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(unsigned from = 0);
void expand();
void add(const T &obj);
int size() const{return this->nrofel;}
T& operator[](const int index);
const T& operator[](const int index) const;
private:
T **data;
unsigned capacity;
unsigned nrofel;
};
template <class T>
Vector<T>::Vector(int size){
this->capacity = size;
this->nrofel = 0;
this->data = new T*[this->capacity];
this->initialize();
}
template <class T>
T& Vector<T>::operator[](int index){
if(index < 0 || index > this->nrofel){
throw("Out of bounds");
}
return *this->data[index];
}
template <class T>
const T& Vector<T>::operator[](int index) const{
if(index < 0 || index > this->nrofel){
throw("Out of bounds");
}
return *this->data[index];
}
template <class T>
void Vector<T>::initialize(unsigned from){
for(size_t i = from; i < this->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] = new T(*this->data[i]);
}
for(size_t i = 0; i < this->nrofel; i++){
delete this->data[i];
}
delete[] data;
this->data = tempData;
this->initialize(this->nrofel);
}
template <class T>
void Vector<T>::add(const T &obj){
if(this->nrofel >= this->capacity){
this->expand();
}
this->data[this->nrofel++] = new T(obj);
}
我的 add 方法处理对象和几乎任何值,但是如何使该方法可用于从文件输入到数组中?
【问题讨论】:
标签: c++ class templates methods dynamic