Using inheritance and templates, Ive to sort by name an array of employee information. I got three classes, Payroll, SimpleVector and SortingVector. Payroll contains all the user info attributes, SimpleVector creates a dynamic array of type Payroll to store all the user info. Now do SortingVector class is in charge of sorting the array by names. But I keep getting many different errors whenever I tried to fix a previous error.
Posting now each class:
Payroll class
#pragma once
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Payroll {
private:
int empNumber;
string name;
double hours;
double payRate;
double grossPay;
int *aptr;
int arraySize;
public:
Payroll(int size);
Payroll();
Payroll(const Payroll & aPayroll);
~Payroll();
//Mutators
void setVector(Payroll &aPayroll);
void setEmpNumber(int empNumber);
void setName(string name);
void setHours(double hours);
void setPayRate(double payRate);
void setGrossPay(double grossPay);
//Accessors
int getEmpNumber()const;
string getName()const;
double getHours()const;
double getPayRate()const;
double getGrossPay()const;
Payroll &operator =(const Payroll &aPayroll);
bool operator ==(const Payroll &aPayroll) const;
friend ostream & operator << (ostream & output, const Payroll & aPayroll);
friend istream & operator >> (istream & input, Payroll & aPayroll);
};
//cpp
Payroll::Payroll() : empNumber(0), name(""), hours(0.00), payRate(0.00), grossPay(0.00) {}
Payroll::Payroll(const Payroll & aPayroll) : empNumber(aPayroll.empNumber), name(aPayroll.name), hours(aPayroll.hours),
payRate(aPayroll.payRate), grossPay(aPayroll.grossPay) {}
Payroll::~Payroll() {
}
//Mutators
void Payroll::setEmpNumber(int empNumber) {
this->empNumber = empNumber;
}
void Payroll::setName(string name) {
this->name = name;
}
void Payroll::setHours(double hours) {
this->hours = hours;
}
void Payroll::setPayRate(double payRate) {
this->payRate = payRate;
}
void Payroll::setGrossPay(double grossPay) {
this->grossPay = grossPay;
}
//Accessors
int Payroll::getEmpNumber()const {
return(this->empNumber);
}
string Payroll::getName()const {
return(this->name);
}
double Payroll::getHours()const {
return(this->hours);
}
double Payroll::getPayRate()const {
return(this->payRate);
}
double Payroll::getGrossPay()const {
return(this-> hours * payRate);
}
Payroll &Payroll::operator = (const Payroll &aPayroll) {
this->name = aPayroll.name;
this->empNumber = aPayroll.empNumber;
this->hours = aPayroll.hours;
this->payRate = aPayroll.payRate;
this->grossPay = aPayroll.grossPay;
return(*this);
}
bool Payroll::operator ==(const Payroll &aPayroll) const {
bool equal = this->name == aPayroll.name;
return(equal);
}
SIMPLEVECTOR CLASS
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <cstdlib>
#include "C:\Users\Jorge\Dropbox\PayRoll Class\Payroll.h"
using namespace std;
template <class type>
class SimpleVector {
private:
type *aptr;
int arraySize;
void subError();
public:
SimpleVector(int);
SimpleVector(const SimpleVector &aVector);
~SimpleVector();
int size() {
return arraySize;
}
type &operator [](int);
void print();
};
template <class type>
SimpleVector<type>::SimpleVector(int s) {
arraySize = s;
aptr = new type[s];
for (int count = 0; count < arraySize; count++)
aptr[count] = type();
}
template <class type>
SimpleVector<type>::SimpleVector(const SimpleVector &aVector) {
arraySize = aVector.arraySize;
aptr = new type[arraySize];
for (int count = 0; count < arraySize; count++)
aptr[count] = aVector[count];
}
template <class type>
SimpleVector<type>::~SimpleVector(){
if (arraySize > 0)
delete[] aptr;
}
template <class type>
void SimpleVector<type>::subError() {
cout << "ERROR: Subscript out of range.\n";
exit(0);
}
template <class type>
type &SimpleVector<type>::operator[](int sub) {
if (sub < 0 || sub >= arraySize)
subError();
return aptr[sub];
}
template <class type>
void SimpleVector<type>::print() {
for (int k = 0; k < arraySize; k++)
cout << aptr[k] << " ";
cout << endl;
}
#endif
SORTINGARRAY CLASS
#ifndef SortingVector_h
#define SortingVector_h
#include "SimpleVector.h"
#include <iostream>
#include <string>
template <class t>
class SortingVector : public SimpleVector<t> {
public:
SortingVector(int s) : SimpleVector<t>(s) {}
SortingVector(SortingVector &aSort);
SortingVector(SimpleVector<t> &aVector) : SimpleVector<t>(aVector) {}
void sortingByName(SimpleVector<Payroll> &aVector);
};
#endif
template <class t>
SortingVector<t>::SortingVector(SortingVector &aVector) : SimpleVector<t>(aVector) {}
template <class t>
void SortingVector<t>::sortingByName(SimpleVector<Payroll> &aVector) {
bool swap;
SortingVector<Payroll> temp;
int x;
do {
swap = false;
for (int i = 0; i < aVector.arraySize; i++) {
x = strcmp(aVector[i], aVector[i + 1]);
if (x > 0) {
temp = aVector[i];
aVector[i] = aVector[i + 1];
aVector[i + 1] = temp;
swap = true;
}
}
} while (swap);
}
The errors right now are:
Error 2 error C2248: 'SimpleVector<Payroll>::arraySize' : cannot access private member declared in class 'SimpleVector<Payroll>' c:\users\jorge\dropbox\simplevector\simplevector\sortingvector.h 39 1 SimpleVector
Error 1 error C2512: 'SortingVector<Payroll>' : no appropriate default constructor available c:\users\jorge\dropbox\simplevector\simplevector\sortingvector.h 32 1 SimpleVector
Error 3 error C2664: 'int strcmp(const char *,const char *)' : cannot convert argument 1 from 'Payroll' to 'const char *' c:\users\jorge\dropbox\simplevector\simplevector\sortingvector.h 42 1 SimpleVector
Error 4 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Payroll' (or there is no acceptable conversion) c:\users\jorge\dropbox\simplevector\simplevector\sortingvector.h 45 1 SimpleVector
Error 5 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'SortingVector<Payroll>' (or there is no acceptable conversion) c:\users\jorge\dropbox\simplevector\simplevector\sortingvector.h 47 1 SimpleVector
SortingVector<Payroll> temp(); is not parsed as you expected (vexing parse), you want:
SortingVector<Payroll> temp;
or
SortingVector<Payroll> temp{}; /* since C++11 */
Related
It has been more than a decade since the last time I wrote something in C/C++ and now I have a problem I cannot solve. Basically I have two classes, say CA and CB, where CA looks like a vector and CB looks like a two-dimensional matrix.
The issue that I am facing is that I want to construct an object of type CB and do so by using another object of type CB. Therefore, I pass as a parameter an object of type CB that has been initialized correctly, but when I do that, I get an error of the form ./B.h:97:43: error: no viable overloaded operator[] for type 'const CB<double>'.
The way I copy the object is by relying on the copying mechanism for class CA. Having said that, constructing an object of class CA by using another initialized object of class CA appears to be working fine. So, I am a little bit lost as to what is wrong. I also get additional help from the compiler for my error, but I am not sure how to fix things really. The full error that I receive using g++ is the following:
In file included from main.cpp:1:
./B.h:97:43: error: no viable overloaded operator[] for type 'const CB<double>'
(*theRows)[i] = new CA <DataType>(m[i]);
^ ~
./B.h:105:2: note: in instantiation of member function 'CB<double>::copy' requested here
copy(a);
^
main.cpp:24:16: note: in instantiation of member function 'CB<double>::CB' requested here
CB<double> myPrecious(mycb_c);
^
./B.h:21:27: note: candidate function not viable: 'this' argument has type 'const CB<double>', but method is not marked const
virtual CA<DataType>& operator[] (int index);
^
1 error generated.
There must be something that I do not remember how to do, or most likely, I am not aware of. Note that if you comment the offending line fromm main.cpp (line 24) with the command CB<double> myPrecious(mycb_c);, then the program compiles without a problem and the output is fine.
I tried to create a minimal example and this is as far as I could shrink the code.
Any ideas on how to make the constructor work by using copy? I appreciate your time.
BELOW ARE THE FILES
main.cpp:
#include "B.h"
int main()
{
CA<double> myca_a(3);
CA<double> myca_b(myca_a);
CB<double> mycb_c(2, 3, 3.0);
CB<double> mycb_d(3, 2, 4.0);
CB<double> mycb_e;
cout << "<separator>" << endl;
cout << myca_a << endl;
cout << "<separator>" << endl;
cout << myca_b << endl;
cout << "<separator>" << endl;
cout << mycb_c << endl;
cout << "<separator>" << endl;
cout << mycb_d << endl;
cout << "<separator>" << endl;
cout << mycb_e << endl;
cout << "<separator>" << endl;
CB<double> myPrecious(mycb_c);
return 0;
}
A.h:
#include <iostream>
using namespace std;
template <class DataType>
class CA
{
protected:
DataType* paDataType;
int _size;
void copy(const CA<DataType>& ac);
public:
CA();
CA(int n);
CA(int n, const DataType& o);
CA(const CA<DataType>& ac);
virtual ~CA();
int size() const;
DataType& operator [] (int k);
void operator= (const CA<DataType>& ac);
friend ostream& operator<<(ostream& os, CA<DataType>& a) {
os << "[";
for (int i = 0; i < a.size() - 1; i++)
os << a[i] << " ";
os << a[a.size() - 1] << "]";
return os;
}
};
//Empty constructor
template <class DataType>
CA<DataType>::CA()
{
paDataType = new DataType[1];
_size = 1;
}
//Constructor
template <class DataType>
CA<DataType>::CA(int n)
{
paDataType = new DataType[n];
_size = n;
}
//Constructor w/ value
template <class DataType>
CA<DataType>::CA(int n, const DataType& o)
{
paDataType = new DataType[n];
_size = n;
for (int i = 0; i < _size; i++) paDataType[i] = o;
}
//Copy Constructor
template <class DataType>
CA<DataType>::CA(const CA<DataType>& ac)
{
copy(ac);
}
//Copy method
template <class DataType>
void CA<DataType>::copy(const CA<DataType>& ac)
{
paDataType = new DataType[ac._size];
_size = ac._size;
for (int i = 0; i < _size; i++)
paDataType[i] = ac.paDataType[i];
}
//Destructor
template<class DataType>
CA<DataType>::~CA()
{
if (paDataType != NULL)
delete[] paDataType;
paDataType = NULL;
_size = 0;
}
//Size method
template <class DataType>
int CA<DataType>::size() const
{
return _size;
}
//Accessor
template <class DataType>
DataType& CA<DataType>::operator [] (int k)
{
return paDataType[k];
}
//Overloaded assignment operator
template <class DataType>
void CA<DataType>::operator= (const CA<DataType>& ac)
{
if (paDataType != NULL) delete[] paDataType;
copy(ac);
}
B.h:
#include "A.h"
template <class DataType>
class CB : public CA <CA <DataType> >
{
protected:
CA < CA<DataType>* >* theRows;
void copy(const CB<DataType>& m);
void deleteRows();
public:
CB();
CB(int n, int m);
CB(int n, int m, DataType v);
CB(const CB& a);
virtual ~CB();
void operator= (const CB<DataType>& a);
virtual int size() const;
int columns();
int rows();
virtual CA<DataType>& operator[] (int index);
friend ostream& operator<<(ostream& os, CB<DataType>& m) {
int rows = m.rows();
int cols = m.columns();
os << "----------" << endl;
for (int i = 0; i < rows-1; i++) {
for (int j = 0; j < cols-1; j++) {
os << m[i][j] << " ";
}
os << m[i][cols-1] << endl;
}
for (int j = 0; j < cols-1; j++) {
os << m[rows-1][j] << " ";
}
os << m[rows-1][cols-1] << endl;
os << "----------";
return os;
}
};
template <class DataType> CB<DataType>::CB() {
theRows = new CA <CA <DataType>* >(1, NULL);
(*theRows)[0] = new CA <DataType>();
}
template <class DataType>
CB<DataType>::CB(int n, int m)
{
theRows = new CA <CA <DataType>* >(n, NULL);
for (int i = 0; i < n; i++)
{
(*theRows)[i] = NULL;
(*theRows)[i] = new CA <DataType>(m);
}
}
template <class DataType>
CB<DataType>::CB(int n, int m, DataType v)
{
theRows = new CA <CA <DataType>* >(n, NULL);
for (int i = 0; i < n; i++)
{
(*theRows)[i] = new CA <DataType>(m, v);
}
}
template <class DataType>
void CB<DataType>::deleteRows()
{
if (theRows != NULL)
{
for (int i = 0; i < theRows->size(); i++)
{
if ((*theRows)[i] != NULL) delete (*theRows)[i];
(*theRows)[i] = NULL;
}
delete theRows;
}
theRows = NULL;
}
template <class DataType>
CB<DataType>::~CB()
{
deleteRows();
}
template <class DataType>
void CB<DataType>::copy(const CB<DataType>& m)
{
deleteRows();
theRows = new CA <CA <DataType>* >(m.size(), NULL);
for (int i = 0; i < m.size(); i++)
{
(*theRows)[i] = new CA <DataType>(m[i]);
}
}
template <class DataType>
CB<DataType>::CB(const CB<DataType>& a)
{
deleteRows();
copy(a);
}
template <class DataType>
void CB<DataType>::operator= (const CB<DataType>& a)
{
copy(a);
}
template <class DataType>
int CB<DataType>::size() const
{
return theRows->size();
}
template <class DataType>
CA<DataType>& CB<DataType>::operator[] (int index)
{
return (*(*theRows)[index]);
}
template <class DataType>
int CB<DataType>::rows()
{
return theRows->size();
}
template <class DataType>
int CB<DataType>::columns()
{
return (*this)[0].size();
}
The problem is that currently you have overloaded operator[] as a non-const member function of class template CB. This means that the implicit this parameter of this member function is of type CB<DataType>*. Meaning that we can use this member function only with non-const objects.
To solve this problem you need to make it(overload it as) a const member function instead by adding a const as shown below, so that now the implicit this parameter will be of type const CB<DataType>* meaning now it can be used with const objects.
template <class DataType>
class CB : public CA <CA <DataType> >
{
virtual CA<DataType>& operator[] (int index) const; //added const here
//other members here
}
template <class DataType>
CA<DataType>& CB<DataType>::operator[] (int index) const //added const here
{
return (*(*theRows)[index]);
}
//other code here
The program compiles after the modification as can be seen here.
Vehicle header file
#define vehicle_h
#include "date.h"
#include "storable.cpp"
#include <string>
using namespace std;
typedef enum{bike = 1,car = 2,towera = 3} VehicleType;
class Vehicle : public Storable
{
private:
string registrationnumber;
VehicleType type;
int seats;
string companyname;
double pricePerKm;
Date PUCExpirationDate;
public:
Vehicle(
string registrationnumber,
VehicleType type,
int seats,
string companyname,
double pricePerKm,
Date PUCExpirationDate, long recordID);
string getregistrationnumber() const;
VehicleType getVehicleType() const;
string getVehicleTypeName() const;
int getseats() const;
string getcompanyName() const;
double getPricePerKm() const;
Date getPUCExpirationDate() const;
void setPricePerKm(double newPrice);
void display() const;
string toString() const;
void setDataForm (Storable * s);
};
#endif // vehicle
Vehicle
#include "Vehicle.h"
#include "STRING_HELPER.h"
const char DELIMETER =';';
Vehicle :: Vehicle(string registrationnumber,VehicleType type,int seats,
string companyName , double pricePerKm , Date PUCExpirationDate , long recordID=0):Storable(recordID)
{
this->registrationnumber =registrationnumber;
this->type= type;
this->seats = seats;
this-> companyname = companyname;
this->pricePerKm = pricePerKm;
this->PUCExpirationDate = PUCExpirationDate;
}
string Vehicle ::getregistrationnumber() const
{
return this->registrationnumber;
}
VehicleType Vehicle::getVehicleType() const
{
return this->type;
}
int Vehicle::getseats() const
{
return this->seats;
}
string Vehicle::getcompanyName() const
{
return this->companyname;
}
double Vehicle::getPricePerKm() const
{
return this->pricePerKm;
}
Date Vehicle::getPUCExpirationDate() const
{
return this->PUCExpirationDate;
}
void Vehicle::setPricePerKm( double newprice)
{
this->pricePerKm= newprice;
}
string Vehicle::getVehicleTypeName() const
{
switch(this->type)
{
case VehicleType:: bike:
return "bike";
case VehicleType:: car:
return "car";
case VehicleType:: towera:
return "Tower";
default:
return " ";
}
}
void Vehicle::display() const
{
cout<< "Vehicle Details :"<<endl;
cout<< "Registration Number : "<< this->registrationnumber<<endl;
cout<< "Vehicle Type : "<< this->type<<endl;
cout<< "No of seats : "<< this->seats<<endl;
cout<< "Company Name : "<< this->companyname<<endl;
cout<< "Price PER Km : "<< this->pricePerKm<<endl;
cout<< "PUC ExpirationDate : "<< this->PUCExpirationDate.toString()<<endl;
}
string Vehicle::toString() const
{
stringstream ss;
ss<<recordID<< DELIMETER<< registrationnumber<< DELIMETER<< type<< DELIMETER<< seats<< DELIMETER<< companyname<< DELIMETER
<< to_string(pricePerKm)<< DELIMETER<< PUCExpirationDate.toString();
return ss.str();
}
void Vehicle ::setDataForm(Storable *s)
{
Vehicle *v = dynamic_cast<Vehicle *> (s);
if(v)
{
this->registrationnumber= v->registrationnumber;
this->type= v->type;
this->companyname= v->companyname;
this->seats= v->seats;
this->pricePerKm = v->pricePerKm;
this->PUCExpirationDate= v->PUCExpirationDate;
}
}
Template Table header file
#define table_h
#include "storable.cpp"
#include "Vehicle.h"
#include "error.cpp"
#include <vector>
#include<string>
#include <fstream>
using namespace std;
template <class T> class Table {
private:
string fileName;
fstream fileStream;
vector<Storable *> * records = NULL;
T * getRefOfRecord(long recordID) const throw(IOError);
void writeToFile () throw(IOError);
T * addNewRecord (T data) const throw (IOError);
void updateRecord (T updateRecord) const throw (IOError);
public:
Table(string fileName) throw (MemoryError);
~Table();
long getNextRecordId() const;
const T* const getRecordForld(long recordId) const throw(IOError);
friend class Database;
};
#endif // table_h
Template table .cpp
#include "Table.h"
#include<iostream>
using namespace std;
template <class T> Table<T> ::Table(string fileName)
throw(MemoryError)
{
this->fileName = fileName;
this->records = new vector<Storable *> ();
if(!this->records)
{
throw MemoryError();
}
}
template <class T> long Table<T> ::getNextRecordId() const
{
return this->records->size()+1;
}
template <class T> T* Table<T> ::addNewRecord (T record) const throw (IOError)
{
T *newRecord = new T(record);
if(!newRecord)
{
throw new MemoryError();
}
newRecord->recordId = this->getNextRecordId();
this->records->push_back(newRecord);
try
{
this->writeToFile();
}
catch(IOError error)
{
this->records->pop_back();
delete newRecord;
throw;
}
return newRecord;
}
template <class T> void Table<T> ::updateRecord(T updateRecord) const throw(IOError)
{
for(auto & record:*this->records)
{
if(record->getRecordID()== updateRecord.getRecordID())
{
T * ptr = dynamic_cast<T*> (record);
if(ptr)
{
T oldRecord = T(* ptr);
record->setDataFrom(&updateRecord);
try
{
this->writeToFile();
return;
}
catch(IOError error)
{
record->setDataFrom (&oldRecord);
throw;
}
}
}
}
throw MemoryError();
}
template <class T> void Table<T> ::writeToFile() throw (IOError)
{
this->fileStream.open(fileName,ios::out | ios::trunc);
if(!this->fileStream)
{
throw IOError();
}
for(auto & record: *records)
{
fileStream <<record->toString()<<endl;
}
this->fileStream.close();
}
template <class T> const T* const Table<T> ::getRecordForld(long recordId) const throw(IOError)
{
try
{
return this->getRefOfRecord(recordId);
}
catch(IOError)
{
throw;
}
}
template <class T> T* Table<T> ::getRefOfRecord(long recordId) const throw (IOError)
{
for(auto &record :*records)
{
if(record->getRecordID()== recordId)
{
return dynamic_cast<T*> (record);
}
}
throw IOError();
}
template <class T> Table<T> ::~Table()
{
for(auto & record : *this->records)
{
delete dynamic_cast<T*> (record);
}
this->records->clear();
this->records->shrink_to_fit();
delete this->records;
}
the template class working fine with the other class such as user or trip but with vehicle class I am getting this error
give the error invalid abstract parameter type 'Vehicle'
I am stuck in this place two three day ago I terid but didn't find any clue !!
I am a beginner at c++ and I am coding a program that stores data into a BST template class the being another class called log_t that stores the variables, I am trying to use the inorder method from the BST class to reference a vector from main, to input the values into and be able to use it in the main class
my main class
int main(int argc, char* argv[])
{
BST<log_t> l;
string infilename = "";
string filePath = "data\\";
string files[1] = {
filePath + "MetData-31-3a.csv"
//filePath + "Jan20071toDec31abcdefghijklmnopq",
//filePath + "Jan20081toDec31abcdefghijklmnopq",
//filePath + "MetData_Jan01-2010-Jan01-2011-ALL"
};
/// checks if file can open
for (int i = 0; i < 1; i++) {
infilename = files[i];
ifstream infile(infilename);
if (!infile.is_open())
{
cout << "unable to read file" << files[i] << endl;
}
else
{
cout << "reading file" << files[i] << endl;
}
/* parse sensor data csv file */
string tmp;
getline(infile, tmp); // skip the first line
while (getline(infile, tmp))
{
// if successfully parsed then append into vector
log_t logline;
if (ParseLog(tmp, logline))
l.insert(logline);
}
}
cout << " end with reading file" << endl;
/* aggregate/filter logs */
Vector<log_t> vec;
l.inorder(vec);
/* prompt menu */
// this array stores all the menu option callback functions
void(*funs[])(const Vector<log_t> & vec) = { NULL, &option1, &option2, &option3, &option4, &option5,&option6 };
// keep printing menu in loop
while (true)
{
// prompt menu and ask user to select option
int choice = PromptMenu();
// check validity of choice
if (choice < 1 || choice > 6)
{
cout << "invalid choice" << endl;
}
else
{
cout << endl;
// call menu option handler
(funs[choice])(vec);
}
}
system("pause");
return -1;
}
my BST class
#include <string>
#include <iostream>
#include <stream>
#include <iomanip>
#include <stream>
#include "date.h"
#include "times.h"
#include "log_t.h"
#include "Vector.h"
using namespace std;
template <class T>
class BST {
private:
struct Node {
T num;
Node* left;
Node* right;
};
Node* root = NULL;
Node* insert(Node* node, T x);
Node* newnode(T num);
void removeprivate(T num, Node* parent);
T findsmallestprivate(Node* ptr);
void inorderprivate(Node* ptr, void (BST<T>::* FT)(T&), Vector<log_t>const& log);
void postorderprivate(Node* ptr, void (BST<T>::* FT)(T&));
void preorderprivate(Node* ptr, void (BST<T>::* FT)(T&));
//void inorderprivate(Node* ptr);
//void postorderprivate(Node* ptr);
//void preorderprivate(Node* ptr);
void removematch(Node* parent, Node* match, bool left);
public:
void insert(T num);
void remove(T num);
void removerootmatch();
T findsmallest();
void inorder(Vector<log_t>const& log);
void postorder();
void preorder();
void print(T& p) { cout << p << " "; };
};
template <class T>
void BST<T>::inorder(Vector<log_t>const& log) {
inorderprivate(root,print,log);
}
template <class T>
void BST<T>::inorderprivate(Node* ptr, void (BST<T>::* FT)(T&), Vector<log_t>const&
log) {
if (root != NULL)
{
if (ptr->left != NULL)
{
inorderprivate(ptr->left, FT);
}
(this->*FT)(log);
log.Append( ptr->num);
if (ptr->right != NULL)
{
inorderprivate(ptr->right, FT);
}
}
else
{
cout << "tree is empty";
}
}
my log_t class the T type
#pragma once
#ifndef LOG_T_H
#define LOG_T_H
#include <iostream>
#include <stream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <stream>
#include "date.h"
#include "times.h"
#include "BST.h"
class log_t
{
public:
log_t();
log_t(log_t& log);
float gettemp();
float getwind();
float getsolar();
void setwind(float wind);
void setsolar(float rad);
void settemp(float temp);
Date date;
Times time;
private:
float wind_speed;
float solar_radiation;
float air_temperature;
};
log_t::log_t()
{
wind_speed = 0;
solar_radiation = 0;
air_temperature = 0;
}
log_t::log_t(log_t& log) {
wind_speed = log.wind_speed;
solar_radiation = log.solar_radiation;
air_temperature = log.air_temperature;
date.SetDate(log.date.GetDay(), log.date.GetMonth(), log.date.GetYear());
time.SetHour(log.time.GetHour());
time.SetMinute(log.time.GetMinute());
}
float log_t:: gettemp()
{
return air_temperature;
}
float log_t::getwind() {
return wind_speed;
}
float log_t::getsolar() {
return solar_radiation;
}
void log_t::setwind(float wind)
{
wind_speed = wind;
}
void log_t::setsolar(float rad)
{
solar_radiation = rad;
}
void log_t::settemp(float temp)
{
air_temperature = temp;
}
#endif // LOG_T_H
my vector class
#pragma once
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <stream>
#include <string>
template <class T>
class Vector
{
public:
Vector();
Vector(int capacity);
Vector(const Vector& vec);
Vector& operator=(const Vector& vec);
~Vector();
int GetSize() const;
void Expand();
T& GetLast();
void Append(const T& val);
T& operator[](int idx);
const T& operator[](int idx) const;
private:
T* elems;
int capacity;/** < int capacity, stores the size of the array */
int count;
void CopyFrom(const Vector& vec);
};
template <class T>
inline Vector<T>::Vector() : elems(nullptr), capacity(0), count(0)
{
}
template <class T>
inline Vector<T>::Vector(int capacity)
: elems(new T[capacity]()), capacity(capacity), count(0)
{
}
template <class T>
inline Vector<T>::Vector(const Vector& vec)
{
CopyFrom(vec);
}
template <class T>
inline Vector<T>& Vector<T>::operator=(const Vector& vec)
{
if (elems)
delete[] elems;
CopyFrom(vec);
return *this;
}
template <class T>
inline Vector<T>::~Vector()
{
if (elems)
delete[] elems;
}
template <class T>
inline int Vector<T>::GetSize() const
{
return count;
}
template <class T>
inline void Vector<T>::Expand()
{
++count;
if (count > capacity)
if (capacity)
capacity *= 2;
else
capacity = 4;
T* tmp = new T[capacity]();
for (int i = 0; i < count - 1; ++i)
tmp[i] = elems[I];
if (elems)
delete[] elems;
elems = tmp;
}
template <class T>
inline T& Vector<T>::GetLast()
{
return elems[count - 1];
}
template <class T>
inline void Vector<T>::Append(const T& oval)
{
Expand();
GetLast() = val;
}
template <class T>
inline T& Vector<T>::operator[](int idx)
{
return elems[idx];
}
template <class T>
inline const T& Vector<T>::operator[](int idx) const
{
return elems[idx];
}
template <class T>
inline void Vector<T>::CopyFrom(const Vector& vec)
{
elems = new T[vec.capacity]();
capacity = vec.capacity;
count = vec.count;
for (int i = 0; i < count; ++i)
elems[i] = vec.elems[i];
}
#endif //VECTOR_H
the errors that keep showing up are
Severity Code Description Project File Line Suppression State
Error (active) E0147 declaration is incompatible with "void BST::inorder(const Vector<> &log)" (declared at line 241 of "C:\Users\Frances\Documents\A2\A2\BST.h") A2 C:\Users\Frances\Documents\A2\A2\BST.h 241
Severity Code Description Project File Line Suppression State
Error C2065 'log_t': undeclared identifier A2 C:\Users\Frances\Documents\A2\A2\BST.h 33
Severity Code Description Project File Line Suppression State
Error C2923 'Vector': 'log_t' is not a valid template type argument for parameter 'T' A2 C:\Users\Frances\Documents\A2\A2\BST.h 33
could someone help me figure out what it is that's causing this or what I am doing wrong, I have been trying to find an answer for hours and haven't been successful thank you
I have a assignment where I'm suppose to build template using these specifications.
ISet is a container that holds values of a certain where order doesn't matter and
which does not allow duplicates (or multiples).
A dynamically allocated array of type T should be used as an internal data structure for the Set.
The Set should inherit from the ISet interface below - this must not be modified:
template <typename T>
class ISet
{
public:
virtual bool insert (T element) = 0;
virtual bool remove (T element) = 0;
virtual int size () const = 0;
};
• insert (T element): adds elements to the set and returns true provided that
the element is not already present in the quantity (in which case the element is not added and false is returned).
• remove (T element): removes elements from the set and returns true.
If the element is missing in the quantity, false returns.
• size (): returns the number of elements in the set.
In addition to the member functions, you must implement constructor, destructor, copy constructor
and assignment operator.
And so far have I come up with this code:
#pragma once
#include <string>
#include <iostream>
using namespace std;
template <class T>
class ISet
{
public:
virtual bool insert(T element) = 0;
virtual bool remove(T element) = 0;
virtual int size() const = 0;
};
#pragma once
#include "ISet.h"
template <class T>
class Set : public ISet<T>
{
public:
Set(string name);
~Set();
Set(const Set &origin);
//Set& operator=(const Set &origin);
bool insert(T element);
bool remove(T element);
int size()const;
private:
string name;
T *arr;
int cap, nrOfElement;
};
template<class T>
Set<T>::Set(string name)
{
this->name = name;
this->cap = 10;
this->nrOfElement = 0;
this->arr = new T[this->cap];
}
template<class T>
Set<T>::~Set()
{
delete[] arr;
}
template<class T>
Set<T>::Set(const Set & origin)
{
this->nrOfElement = origin.nrOfElement;
this->cap = origin.cap;
arr = new T*[cap];
for (int i = 0; i < nrOfElement; i++)
{
arr[i] = origin.arr[i];
}
}
template<class T>
bool Set<T>::insert(T element)
{
bool found = false;
if (nrOfElement == 0)
{
this->arr[0] = element;
this->nrOfElement++;
}
else
{
for (int i = 0; i < this->nrOfElement; i++)
{
if (this->arr[i] == element)
{
i = this->nrOfElement;
found = true;
}
}
if (found == false)
{
this->arr[nrOfElement++] = element;
}
}
return found;
}
template<class T>
bool Set<T>::remove(T element)
{
bool removed = false;
for (int i = 0; i < this->nrOfElement; i++)
{
if (this->arr[i] == element)
{
this->arr[i] = this->arr[nrOfElement];
nrOfElement--;
removed = true;
}
}
return removed;
}
template<class T>
int Set<T>::size() const
{
return this->nrOfElement;
}
And my problems starts when I start to test this code by adding the different data-type we are suppose to test the template against.
#include "Set.h"
#include "ISet.h"
#include "Runner.h"
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
Set<string> test("test");
test.insert("lol");
cout << test.size();
test.remove("lol");
cout << test.size();
Set<Runner> test2("test");
getchar();
return 0;
}
Getting the error saying that "No operator found which takes a left-hand operand type of 'Runner'. So I have to create a operator== that handles this but don't know?
Runner class looks like this:
#pragma once
#include "Competitor.h"
#include <string>
using namespace std;
class Runner : public Competitor
{
public:
Runner();
Runner(string firstName, string lastName, int startNr);
~Runner();
void addResult(int resultTime);
int getResult() const;
string toString() const;
Runner *clone() const;
private:
int resultTime;
};
#include "Runner.h"
Runner::Runner()
{
this->resultTime = 0;
}
Runner::Runner(string firstName, string lastName, int startNr) : Competitor(firstName, lastName, startNr)
{
this->resultTime = 0;
}
Runner::~Runner()
{
}
void Runner::addResult(int resultTime)
{
this->resultTime = resultTime;
}
int Runner::getResult() const
{
return this->resultTime;
}
string Runner::toString() const
{
return (to_string(this->resultTime) + " sec");
}
Runner * Runner::clone() const
{
return new Runner(*this);
}
How do I build a operator== that will work for this?
You need to add operator== to the Runner class:
bool operator==(const Runner& other) const;
i am required to read a file with data of this format (Date, ID, Activity, Qty, Price) in the main test class. I'm supposed to read and store the "Date" values into int day,month,year of type Date, followed by "ID, Activity, Qty, Price" of stock class.
02/08/2011, ABC, BUY, 100, 20.00
05/08/2011, ABC, BUY, 20, 24.00
06/08/2011, ABC, BUY, 200, 36.00
i stored the values accordingly to Stock() constructor and store all data via push_back() in my own "Vector" class. what must i add/ edit so that i can retrieve the rows of data in Vector and get(Date, ID, Activity, Qty, Price) and make calculations for qty and price.
#include"Vector.h"
#include"Date.h"
#include"Stock.h"
#include<iomanip>
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main(){
string stockcode;
string act;
int qty;
double p;
int d,m,y;
char x;
//declare file stream variables
ifstream inFile;
ofstream outFile;
//open the file
inFile.open("share-data.txt");
//code for data manipulation
cout << fixed << showpoint << setprecision(2);
while(!inFile.eof()){
inFile>> d >> x >> m >> x >> y >> x
>> stockcode >> act >> qty >> x >> p;
Stock s1(d,m,y,stockcode,act,qty,p);
stockcode = stockcode.substr(0, stockcode.length()-1);
act = act.substr(0, act.length()-1);
Stock s1(d,m,y,stockcode,act,qty,p);
stockList.push_back(s1);
}
inFile.close();
system("PAUSE");
return 0;
}
i have my own Vector class which is needed for this assignment because i am not allowed to use #include default vector
#include<iostream>
using namespace std;
template <class T>
class Vector
{
public:
Vector(); // default constructor
virtual ~Vector() {}; //destructor
bool isEmpty() const;
bool isFull() const;
void print() const;
void push_back(T);
T pop_back();
T at(int i);
int Size();
//Vector<T> operator +=(T);
private:
int size;
T list[100];
};
template <class T>
Vector<T>::Vector()
{
size = 0;
}
template <class T>
Vector<T> Vector<T>::operator +=(T i)
{
this->push_back(i);
return *this;
}
template <class T>
bool Vector<T>::isEmpty() const
{
return (size == 0);
}
template <class T>
bool Vector<T>::isFull() const
{
return (size == 100);
}
template <class T>
void Vector<T>::push_back(T x)
{
list[size] = x;
size++;
}
template <class T>
T Vector<T>::operator[](T i)
{
return list[i];
}
template <class T>
T Vector<T>::at(int i)
{
if(i<size)
return list[i];
throw 10;
}
template <class T>
T Vector<T>::pop_back()
{
T y;
size--;
y= list[size];
return y;
}
template <class T>
void Vector<T>::print() const
{
for (int i = 0; i < size; i++)
cout << list[i] << " ";
cout << endl;
}
template <class T>
int Vector<T>::Size()
{
return size;
}
and here's my Stock class
#include"Date.h"
Stock::Stock()
{
stockID="";
act="";
qty=0;
price=0.0;
}
Stock::Stock(int d, int m , int y, string id,string a, int q, double p)
:date(d,m,y){
stockID = id;
act = a;
qty = q;
price = p;
}
.
.
.
use string::substr
act = act.substr(0, act.length()-1);
You can do the same for the other string variables.