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 !!
Related
I'm storing my class object in the binary file but I'm getting weird results when I load the data.
Following Code is Loading and Saving Data:
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
using namespace std;
template <class C>
void Load(const char fileName[], C& obj)
{
ifstream in;
in.open(fileName, ios::in | ios::binary);
in.read(reinterpret_cast<char*>(addressof(obj)), sizeof(obj));
in.close();
return;
}
template <class T>
void Save(const char fileName[], T obj)
{
ofstream out;
out.open(fileName, ios::out | ios::binary);
out.write(reinterpret_cast<char const*>(addressof(obj)), sizeof(obj));
stringstream ss;
out.close();
return;
}
class Contact {
public:
int CompareTo(Contact obj)
{
return 1;
}
string ss;
int rollNum;
};
class Data {
public:
Data()
{
}
Contact arr[10];
};
int main()
{
const char fileName[] = "ContactMG.dat";
/*
Data *T = new Data();
for(int i=0;i<10;i++)
T->arr[i].ss = "fahad";
Save(fileName , *T);
*/
Data* d = new Data();
Load(fileName, *d);
for (int i = 0; i < 10; i++)
cout << d->arr[i].ss << endl;
}
/*
Console outPut:
ⁿx
p²x
σß╥Z∙
░▒▓│┤
>
☺Y╩
░‼╩
*/
/* Binary File
#® ® ®
*/
I want to ask how I can store this object in the binary file and load it?
I'm pretty sure the problem is with string but I don't know how to fix it!
I have already known to store strings in binary files but don't know how to store class objects which have string in it
I would introduce a new level of indirection, i.e. functions from_binary and to_binary, and implement your Load and Store in terms of those:
template <class C>
bool Load(const char fileName[], C& obj) {
if (ifstream in{fileName, ios::in | ios::binary}) {
from_binary(in, obj);
return true;
}
return false;
}
template <class T>
bool Save(const char fileName[], T obj) {
if (ofstream out{fileName, ios::out | ios::binary}) {
to_binary(out, obj);
return true;
}
return false;
}
For POD data types, from_binary and to_binary will just do what you already did in Load/Store (beware, however: pointers are PODs but saving an address is pretty much meaningless):
template <class T, typename = enable_if_t<is_pod_v<T>>>
void from_binary(ifstream& in, T& obj) {
in.read(reinterpret_cast<char*>(addressof(obj)), sizeof(obj));
}
template <class T, typename = enable_if_t<is_pod_v<T>>>
void to_binary(ofstream& out, T const& obj) {
out.write(reinterpret_cast<char const*>(addressof(obj)), sizeof(obj));
}
As pointed out in the comments, std::string is not a POD type. I'm going to serialize it by saving the character count and then the actual characters:
void from_binary(ifstream& in, string& str) {
std::size_t stringSize{0};
from_binary(in, stringSize);
str.reserve(stringSize);
for (size_t i = 0; i != stringSize; ++i) {
char ch{};
in.read(&ch, 1);
str.push_back(ch);
}
}
void to_binary(ofstream& out, string const& str) {
auto const stringSize = str.size();
to_binary(out, stringSize);
auto const* cStr = str.c_str();
out.write(cStr, stringSize);
}
Also, I'm going to serialize/deserialize an array by calling to_binary/from_binary on each element of the array:
template <class T, size_t N>
void from_binary(ifstream& in, T (&obj)[N]) {
for (auto& elem : obj) from_binary(in, elem);
}
template <class T, size_t N>
void to_binary(ofstream& out, T const (&obj)[N]) {
for (auto const& elem : obj) to_binary(out, elem);
}
The above functions are enough to implement from_binary and to_binary for your Contact and Data classes:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
template <class T, typename = enable_if_t<is_pod_v<T>>>
void from_binary(ifstream& in, T& obj) {
in.read(reinterpret_cast<char*>(addressof(obj)), sizeof(obj));
}
template <class T, typename = enable_if_t<is_pod_v<T>>>
void to_binary(ofstream& out, T const& obj) {
out.write(reinterpret_cast<char const*>(addressof(obj)), sizeof(obj));
}
void from_binary(ifstream& in, string& str) {
std::size_t stringSize{0};
from_binary(in, stringSize);
str.reserve(stringSize);
for (size_t i = 0; i != stringSize; ++i) {
char ch{};
in.read(&ch, 1);
str.push_back(ch);
}
}
void to_binary(ofstream& out, string const& str) {
auto const stringSize = str.size();
to_binary(out, stringSize);
auto const* cStr = str.c_str();
out.write(cStr, stringSize);
}
template <class T, size_t N>
void from_binary(ifstream& in, T (&obj)[N]) {
for (auto& elem : obj) from_binary(in, elem);
}
template <class T, size_t N>
void to_binary(ofstream& out, T const (&obj)[N]) {
for (auto const& elem : obj) to_binary(out, elem);
}
template <class C>
bool Load(const char fileName[], C& obj) {
if (ifstream in{fileName, ios::in | ios::binary}) {
from_binary(in, obj);
return true;
}
return false;
}
template <class T>
bool Save(const char fileName[], T obj) {
if (ofstream out{fileName, ios::out | ios::binary}) {
to_binary(out, obj);
return true;
}
return false;
}
class Contact {
public:
int CompareTo(Contact obj) { return 1; }
string ss;
int rollNum;
};
void from_binary(ifstream& in, Contact& obj) {
from_binary(in, obj.ss);
from_binary(in, obj.rollNum);
}
void to_binary(ofstream& out, Contact const& obj) {
to_binary(out, obj.ss);
to_binary(out, obj.rollNum);
}
class Data {
public:
Data() {}
Contact arr[10];
};
void from_binary(ifstream& in, Data& obj) { from_binary(in, obj.arr); }
void to_binary(ofstream& out, Data const& obj) { to_binary(out, obj.arr); }
int main() {
const char fileName[] = "ContactMG.dat";
{
Data data;
auto const contactCount = sizeof(data.arr) / sizeof(data.arr[0]);
for (size_t c = 0; c != contactCount; ++c) {
data.arr[c].ss = "some name " + to_string(c);
data.arr[c].rollNum = c;
}
Save(fileName, data);
}
{
Data data;
Load(fileName, data);
for (auto const& contact : data.arr)
cout << "Contact: rollNum=" << contact.rollNum
<< ", ss=" << contact.ss << '\n';
}
}
Output:
Contact: rollNum=0, ss=some name 0
Contact: rollNum=1, ss=some name 1
Contact: rollNum=2, ss=some name 2
Contact: rollNum=3, ss=some name 3
Contact: rollNum=4, ss=some name 4
Contact: rollNum=5, ss=some name 5
Contact: rollNum=6, ss=some name 6
Contact: rollNum=7, ss=some name 7
Contact: rollNum=8, ss=some name 8
Contact: rollNum=9, ss=some name 9
Although this may solve your particular issue, the number of overloads you'll need for from_binary and to_binary will grow very rapidly as your project grows. So I'd definetely check if there's a more comprehensive (and well tested) library solution out there.
My code is as shown below. The problem is inside the int main() function, r.printItems() is not printing anything. What am I missing here?
main.cpp
#include <bits/stdc++.h>
#include "Customer.h"
#include "MenuCreator.h"
#include "FoodItem.h"
MenuCreator m1;
void createCustomer() {
Customer c1("mrg", "m#gmail.com", "9654357", "+91");
}
void createRestaurantItem(Restaurant &rest) {
rest.addItems(FoodItem("t1"));
rest.addItems(FoodItem("D1"));
}
void createMenu() {
m1.createMenu("sg");
Category c1;
c1.setName("Non-veg");
m1.addCategory(c1);
Restaurant r1;
r1.setName("ABC");
r1.setDescription("Test Restaurant");
createRestaurantItem(r1);
c1.addRestaurants(r1);
}
vector<Restaurant> getRestaurantsForCategory(string category) {
return m1.getRestaurantsForCategories(category);
}
int main() {
createCustomer();
createMenu();
for (auto r: getRestaurantsForCategory("Non-veg")) {
r.printItems();
}
return 0;
}
MenuCreator.h
#include <bits/stdc++.h>
#include "Menu.h"
using namespace std;
class MenuCreator {
public:
void createMenu(string name) {
Menu m1;
m1.setName(name);
menu = m1;
}
void addCategory(const Category &categ) {
categories.push_back(categ);
}
const Menu &getMenu() const {
return menu;
}
const vector<Category> &getCategories() const {
return categories;
}
void addRestaurantForCategory(string name, const Restaurant restaurant) {
for(auto categ: categories) {
if (categ.getName() == name) {
categ.addRestaurants(restaurant);
}
}
}
const vector<Restaurant> &getRestaurantsForCategories(string category) {
for(auto categ: categories) {
if(categ.getName() == category) return categ.getRestaurants();
}
}
private:
Menu menu;
vector<Category> categories;
};
Menu.h
#include<bits/stdc++.h>
#include "Category.h"
using namespace std;
class Menu {
public:
const string &getName() const {
return name;
}
void setName(const string &name) {
Menu::name = name;
}
private:
string name;
string description;
vector<Category> categories;
};
Category.h
using namespace std;
class Category {
public:
const string &getName() const {
return name;
}
void setName(const string &name) {
Category::name = name;
}
const string &getDescription() const {
return description;
}
void setDescription(const string &description) {
Category::description = description;
}
const vector<Restaurant> &getRestaurants() const {
return restaurants;
}
void setRestaurants(const vector<Restaurant> &restaurants) {
Category::restaurants = restaurants;
}
void addRestaurants(const Restaurant &rt) {
Category::restaurants.push_back(rt);
}
private:
string name;
string description;
vector<Restaurant> restaurants;
};
FoodItem.h
#include <bits/stdc++.h>
#include <vector>
#include "FoodItem.h"
using namespace std;
class Restaurant {
public:
Restaurant() {
this->id = gen_random(12);
}
virtual ~Restaurant() {
}
const string &getName() const {
return name;
}
void setName(const string &name) {
Restaurant::name = name;
}
const string &getDescription() const {
return description;
}
void setDescription(const string &description) {
Restaurant::description = description;
}
double getLat() const {
return lat;
}
void setLat(double lat) {
Restaurant::lat = lat;
}
double getLang() const {
return lang;
}
void setLang(double lang) {
Restaurant::lang = lang;
}
const string &getImageUrl() const {
return imageUrl;
}
void setImageUrl(const string &imageUrl) {
Restaurant::imageUrl = imageUrl;
}
const string &getVideoUrl() const {
return videoUrl;
}
void setVideoUrl(const string &videoUrl) {
Restaurant::videoUrl = videoUrl;
}
const vector<FoodItem> &getItems() const {
return items;
}
void setItems(const vector<FoodItem> &items) {
Restaurant::items = items;
}
void addItems(const FoodItem &item) {
this->items.push_back(item);
}
string gen_random(const int len) {
string tmp_s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand( (unsigned) time(NULL) * getpid());
tmp_s.reserve(len);
for (int i = 0; i < len; ++i)
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
return tmp_s;
}
const string &getId() const {
return id;
}
void printItems() {
for(auto it: items) {
cout<<"item: "<<it.getName()<<endl;
}
}
private:
string id;
string name;
string description;
double lat;
double lang;
string imageUrl;
string videoUrl;
string createdAt;
string updatedAt;
vector<FoodItem> items;
};
Restaurant.h
#include <bits/stdc++.h>
#include <vector>
#include "FoodItem.h"
using namespace std;
class Restaurant {
public:
Restaurant() {
this->id = gen_random(12);
}
virtual ~Restaurant() {
}
const string &getName() const {
return name;
}
void setName(const string &name) {
Restaurant::name = name;
}
const string &getDescription() const {
return description;
}
void setDescription(const string &description) {
Restaurant::description = description;
}
double getLat() const {
return lat;
}
void setLat(double lat) {
Restaurant::lat = lat;
}
double getLang() const {
return lang;
}
void setLang(double lang) {
Restaurant::lang = lang;
}
const string &getImageUrl() const {
return imageUrl;
}
void setImageUrl(const string &imageUrl) {
Restaurant::imageUrl = imageUrl;
}
const string &getVideoUrl() const {
return videoUrl;
}
void setVideoUrl(const string &videoUrl) {
Restaurant::videoUrl = videoUrl;
}
const vector<FoodItem> &getItems() const {
return items;
}
void setItems(const vector<FoodItem> &items) {
Restaurant::items = items;
}
void addItems(const FoodItem &item) {
this->items.push_back(item);
}
string gen_random(const int len) {
string tmp_s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand( (unsigned) time(NULL) * getpid());
tmp_s.reserve(len);
for (int i = 0; i < len; ++i)
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
return tmp_s;
}
const string &getId() const {
return id;
}
void printItems() {
for(auto it: items) {
cout<<"item: "<<it.getName()<<endl;
}
}
private:
string id;
string name;
string description;
double lat;
double lang;
string imageUrl;
string videoUrl;
string createdAt;
string updatedAt;
vector<FoodItem> items;
};
When createMenu() in main.cpp is setting up the menu, it creates a local Category object named c1 and adds it to the menu, which makes a copy of c1 when pushingnit into the MenuCreator::categories vector. No Restaurant objects had been added to c1 yet when that copy is created. So when a Restaurant is then added to c1 afterwards, the copy is not updated. That is why there are no Restaurant objects in the menu when MenuCreator::getRestaurantsForCategory() tries to return them.
Change createMenu() to fully initialize c1 before adding it to the menu, eg:
void createMenu() {
m1.createMenu("sg");
Category c1;
c1.setName("Non-veg");
Restaurant r1;
r1.setName("ABC");
r1.setDescription("Test Restaurant");
createRestaurantItem(r1);
c1.addRestaurants(r1);
m1.addCategory(c1); // <-- move down here
}
Also, on a side note, the return value of MenuCreator::getRestaurantsForCategories() is undefined if the specified category is not found. Since the return value is a reference to a vector, it needs to either return a static vector that is empty, or else throw an exception.
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
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 */
*EDITED*Thanks for the previous helps.Got this problem now, doesnt like the pr.AddEnumerator(&t); line of the code.But its the same like in the sample task.
The AddEnumerator() is a method in procedure.hpp :
void AddEnumerator(Enumerator<Item>* en){ enor = en;}.
Procedure is the base class.
Also in seqinfileenumerator.hpp:
class SeqInFileEnumerator : public Enumerator<Item>
and in linsearch.hpp:
class LinSearch : public Procedure<Item>
#include <iostream>
#include "linsearch.hpp"
#include "seqinfileenumerator.hpp"
using namespace std;
struct MyPair
{
int azon;
int osszeg;
friend ifstream& operator>>(ifstream& f, MyPair& df);
};
ifstream& operator>>(ifstream& f, MyPair& df)
{
f >> df.azon >> df.osszeg;
return f;
}
class MyLinSearch: public LinSearch <int, true>
{
bool Cond(const int& e) const
{
return e<=-100000;
}
};
class MySeqInFileEnumerator: public SeqInFileEnumerator <MyPair>
{
public:
MySeqInFileEnumerator(char const * p) : SeqInFileEnumerator<MyPair>(p) { }
void Next()
{
MyPair dx;
f >> dx;
df.azon=dx.azon;
df.osszeg=dx.osszeg;
while(dx.azon==df.azon)
{
dx.osszeg+=df.osszeg;
f >> dx;
}
}
};
int main()
{
MyLinSearch pr;
MySeqInFileEnumerator file_enum("input.txt");
pr.AddEnumerator(&file_enum);
pr.Run();
if (pr.Found())
{
cout << "false " << endl;
}
else cout << "true" << endl;
return 0;
}