Агрегаты, шаблоны и динамические векторы

Я продолжаю получать 3 ошибки. Они все связаны с тем, как я собираю шаблоны, я полагаю, но я не могу найти ничего, чтобы помочь мне понять это. Мой учитель не очень понимал, как мы должны получить результат, который он хочет, чтобы мы получили.

In file included from main.cpp:10:
./Table.h:15:9: error: use of class template 'RowAray' requires template arguments

Вот что я написал

RowAray.cpp

#ifndef ROWARAY_H // if constant ROWARAY_H not defined do not execute
#define ROWARAY_H // defines constant ROWARAY_H
#include <iostream>
#include <new>       // Needed for bad_alloc exception
#include <cstdlib>   // Needed for the exit function

template <class T>
class RowAray{
private:
int size;
T *rowData;
void memError();  // Handles memory allocation errors
void subError();  // Handles subscripts out of range
public:
RowAray(T); //used to construct row Array object
~RowAray(){delete [] rowData;} //used to deallocate dynamically allocated memory from Row array
int getSize(){return size;} //inline accessor member function used to return length of Row array
T getData(int i){return (( i >=0&& i < size)?rowData[i]:0);} //
T &operator[](const int &);
};
template <class T>
RowAray<T>::RowAray(T colSize){
size =colSize>1?colSize:1;
// Allocate memory for the array.
try
{
rowData = new T [size];
}
catch (bad_alloc)
{
memError();
}

// Initialize the array.
for (int count = 0; count < size; count++)
*(rowData + count) = rand()%90+10;
}

template <class T>
void RowAray<T>::memError()
{
cout << "ERROR:Cannot allocate memory.\n";
exit(EXIT_FAILURE);
}

template <class T>
void RowAray<T>::subError()
{
cout << "ERROR: Subscript out of range.\n";
exit(EXIT_FAILURE);
}

template <class T>
T &RowAray<T>::operator[](const int &sub)
{
if (sub < 0 || sub >= size)
subError();
else
return rowData[sub];
}
#endif  /* ROWARAY_H */

Table.cpp

#ifndef TABLE_H
#define TABLE_H

#include "RowAray.h"
template <class T>
class Table{
private:
int szRow;
RowAray **records;

public:
Table(int,int); //used to construct Table object
~Table(); //used to deallocate dynamically allocated memory from Table object
int getSzRow(){return szRow;} //used to return row size
int getSize(int row){return records[row>=0?row:0]->getSize();} //used to return column size
T getRec(int, int); //used to return inserted random numbers of 2d arrays
};

template <class T>
Table<T>::Table(int r, int c ){
//Set the row size
this->szRow = r;
//Declare the record array
records = new RowAray*[this->szRow];
//Size each row
int allCol = c;
//Create the record arrays
for(int i=0;i<this->szRow;i++){
records[i]=new RowAray(allCol);
}
}

template <class T>
T Table<T>::getRec(int row, int col){
//if else statement used to return randomly generated numbers of array
if(row >= 0 && row < this->szRow && col >= 0 && col < records[row]->getSize()){
return records[row]->getData(col);
}else{
return 0;
}
}

template <class T>
Table<T>::~Table(){
//Delete each record
for(int i=0;i<this->szRow;i++){
delete records[i];
}
delete []records;
}

#endif  /* TABLE_H */

main.cpp

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;

//User Libraries
#include "RowAray.h"#include "Table.h"
//Global Constants

//Function Prototype
template<class T>
void prntRow(T *,int);
template<class T>
void prntTab(const Table<T> &);

//Execution Begins Here!
int main(int argc, char** argv) {
//Initialize the random seed
srand(static_cast<unsigned int>(time(0)));

//Declare Variables
int rows=3,cols=4;

//Test out the Row with integers and floats
RowAray<int> a(3);
RowAray<float> b(4);
cout<<"Test the Integer Row "<<endl;
prntRow(&a,3);
cout<<"Test the Float Row "<<endl;
prntRow(&b,4);

//Test out the Table with a float
Table<float> tab1(rows,cols);
Table<float> tab2(tab1);
//Table<float> tab3=tab1+tab2;

cout<<"Float Table 3 size is [row,col] = Table 1 + Table 2 ["<<rows<<","<<cols<<"]";
//prntTab(tab3);

//Exit Stage Right
return 0;
}

template<class T>
void prntRow(T *a,int perLine){
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int i=0;i<a->getSize();i++){
cout<<a->getData(i)<<" ";
if(i%perLine==(perLine-1))cout<<endl;
}
cout<<endl;
}

template<class T>
void prntTab(const Table<T> &a){
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int row=0;row<a.getSzRow();row++){
for(int col=0;col<a.getSize();col++){
cout<<setw(8)<<a.getRec(row,col);
}
cout<<endl;
}
cout<<endl;
}

0

Решение

«RowAray» — это шаблон с одним параметром шаблона:

template <class T>
class RowAray

Видишь там? Это шаблон, один параметр шаблона.

Теперь здесь

template <class T>
class Table{
private:
int szRow;
RowAray **records;

Видишь там? Нет параметра шаблона при обращении к RowAray Шаблон, здесь. При использовании шаблона также должны быть указаны его параметры (если они не имеют значения по умолчанию, что здесь не имеет значения).

Тот факт, что здесь вы определяете новый шаблон, Tableс одним параметром шаблона — это не имеет значения.

Вы, вероятно, намеревались использовать

RowAray<T> **records;

Вот; но это просто на основе беглого взгляда на эту кучу кода, так что не верьте мне на слово. Вам нужно выяснить, что вы намеревались сделать здесь, и указать правильный параметр шаблона.

Это не единственная ссылка без параметров в показанном коде. Вам нужно найти и исправить все из них.

Кроме того, вы также сбросили:

using namespace std;

прежде чем продолжить и #includeсборка заголовочных файлов, включая стандартные заголовочные файлы библиотеки. Это плохая практика программирования, и часто создает неуловимые и трудные для понимания ошибки компиляции, если не совершенно неверный код. Вы должны избавиться от using namespace std; а особенно когда куча #includeс участвуют.

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector