C++ saving/loading a vector to a file - c++

I am creating a Calendar application in C++.
Here is my code:
class appointment
{
public:
appointment(string aDate, string aTime, string aType,
string aLocation, string aComments, bool aIsImportant,
string aReminderDate, string aReminderTime)
{
appDate = aDate;
appTime = aTime;
appType = aType;
appLocation = aLocation;
appComments = aComments;
appIsImportant = aIsImportant;
appReminderDate = aReminderDate;
appReminderTime = aReminderTime;
}
void setDate(string aDate)
{
appDate = aDate;
}
void setTime(string aTime)
{
appTime = aTime;
}
void setType(string aType)
{
appType = aType;
}
void setLocation(string aLocation)
{
appLocation = aLocation;
}
void setComments(string aComments)
{
appComments = aComments;
}
void setIsImportant(bool aIsImportant)
{
appIsImportant = aIsImportant;
}
void setReminderDate(string aReminderDate)
{
appReminderDate = aReminderDate;
}
void setReminderTime(string aReminderTime)
{
appReminderTime = aReminderTime;
}
string getDate()
{
return appDate;
}
string getTime()
{
return appTime;
}
string getType()
{
return appType;
}
string getLocation()
{
return appLocation;
}
string getComments()
{
return appComments;
}
bool getIsImportant()
{
return appIsImportant;
}
string getReminderDate()
{
return appReminderDate;
}
string getReminderTime()
{
return appReminderTime;
}
private:
appointment();
string appDate;
string appTime;
string appType;
string appLocation;
string appComments;
bool appIsImportant;
string appReminderDate;
string appReminderTime;
//person owner;
};
class calendar
{
public:
calendar()
{
loadFromFile();
}
~calendar()
{
saveToFile();
}
void createAppointment(string aDate, string aTime, string aType,
string aLocation, string aComments, bool aIsImportant,
string aReminderDate, string aReminderTime)
{
appointment newAppointment(string aDate, string aTime, string aType,
string aLocation, string aComments, bool aIsImportant,
string aReminderDate, string aReminderTime);
//appointments.resize(appointments.size() + 1,newAppointment);
}
private:
vector<appointment> appointments;
string calCurrentDate;
string calCurrentTime;
void loadFromFile()
{
//Code to load appointments from file
}
void saveToFile()
{
//Code to save appointments to file
}
};
Can I please have some help with the following:
When the constructor is called, I want to load a file (loadFromFile() method) of appointment objects and set the 'appointments' variable to have the contents of this file. After the saveToFile() method,I want to save the contents of the appointment vector to file.
Also, when the createAppointment() method is called, I want to increase the size of the vector by 1, and add the contents to the vector. I am not sure of the correct code.
Update Saving/Loading from files
void loadFromFile()
{
ifstream iStream("file.ext", ios::binary);
fileHeader_t fHeader;
iStream.read((char*)&fHeader, sizeof(fileHeader_t));
if (fHeader.magicNumber = 0xDEADBEAF)
{
appointments.resize(fHeader.appointmentCount); iStream.read((char*)&appointments[0], fHeader.appointmentCount * sizeof(appointment));
}
}
void saveToFile()
{
ofstream oStream("file.ext", ios::binary);
fileHeader_t fHeader;
fHeader.magicNumber = 0xDEADBEAF;
fHeader.appointmentCount = appointments.size();
oStream.write((char*)&fHeader, sizeof(fileHeader_t));
oStream.write((char*)&appointments[0], sizeof(appointment) * appointments.size());
}

Vectors are supposedly contiguous, so you shouldn't have any problem about loading them using ifstream, if I were you I'd create a basic header for your binary file with something like :
struct fileHeader_s
{
DWORD magicNumber;
size_t appointmentsCount;
}fileHeader_t;
Then, in a loop, just read each item in an appointment value, and use appointments.push_back( item );
You should do the same in createAppointment, don't resize the vector, just do push_back(newAppointment);

You're going to have to come up with your own file format (i.e. save each record on a line manually), or use something like Boost::serialization.

Related

Class does not persist vector of objects after addition

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.

LinkedQueue implementation used to store flights

I'm trying to implement a LinkedQueue Structure in c++ to store the data of some flights.
So, first of all I have to read a csv file, what provides the data to store.
The LinkedQueue must work this way: the atributes of each Flight has to be stored using the Flight class, and then the LinkedQueue must have a specific nodes called FlightNode to finally store flights.
My code isn't compiling because i can't implement the getNext() function in a correct way.
I'm giving my code below with the implementation of each class. If you guys can make any suggestion it will be very helpfull.
Thank you a lot!!
This is my header class for Flight.h:
class Flight {
public:
Flight();
virtual ~Flight();
string getID();
void setID(string new_id);
string getOrigen();
void setOrigen(string new_origen);
string getDesti();
void setDesti(string new_desti);
string getHora();
void setHora(string new_hora);
private:
string id;
string origen;
string desti;
string hora_sortida;
};
Flight.cpp:
Flight::Flight() {
}
Flight::~Flight() {
}
string Flight::getID(){
return id;
}
string Flight::getOrigen(){
return origen;
}
string Flight::getDesti(){
return desti;
}
string Flight::getHora(){
return hora_sortida;
}
void Flight::setID(string new_id){
id = new_id;
}
void Flight::setOrigen(string new_origen){
origen = new_origen;
}
void Flight::setDesti(string new_desti){
desti = new_desti;
}
void Flight::setHora(string new_hora){
hora_sortida = new_hora;
}
FlightNode.h:
class FlightNode {
public:
FlightNode(Flight& f);
FlightNode(const FlightNode& orig);
virtual ~FlightNode();
FlightNode* getNext();
void setNext(FlightNode* n);
Flight& getElement();
private:
Flight* _element;
FlightNode* _next;
};
FlightNode.cpp:
FlightNode::FlightNode(Flight& f) {
this->_element = &f;
this->_next = nullptr;
}
FlightNode::FlightNode(const FlightNode& orig) {
}
FlightNode::~FlightNode() {
}
FlightNode* FlightNode::getNext(){
return this->_next;
}
void FlightNode::setNext(FlightNode* n){
this->_next = n;
}
Flight& FlightNode::getElement(){
//Don't know how to implement this one, because I declared _element as a pointer but what I need here is to return a reference.
}
main.cpp:
string id;
string origen;
string desti;
string hora;
fstream fin;
fin.open("flights.csv", ios::in);
string line, word;
string id, origen, desti, hora;
while (getline(fin, line)) {
stringstream in(line);
Flight* new_flight = new Flight;
for (int i = 0; getline(in, word, ','); ++i) {
switch (i) {
case 0:
new_flight->setID(word);
break;
case 1:
new_flight->setOrigen(word);
break;
case 2:
new_flight->setDesti(word);
break;
case 3:
new_flight->setHora(word);
break;
}
}
cout << "id:" << new_flight->getID() << " origen:" << new_flight->getOrigen() << " desti: " << new_flight->getDesti() << endl;
queue.enqueue(*new_flight);
}
You can just return the reference behind the pointer:
return *_element;
However, if you plan to do so please ensure that the pointer is not null at the time of the above dereference.

Error: identifier classname is undefined? Getting this for all the classes I've made in the file

This is the code
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
class FIXML {
private: Order Order_object = new Order();
public:
Order getOrder_object()
{
return Order_object;
}
void setOrder_object(Order Order_object)
{
this->Order_object = Order_object;
}
};
class Order {
public:
string ClOrdID = "123456";
string Side = "2";
string TransactTm = "2001-09-11T09:30:47-05:00";
string OrdTyp = "2";
string Px = "93.25";
string Acct = "26522154";
Hdr Hdr_object = Hdr();
Instrmt Instrmt_object = Instrmt();
OrdQty OrdQty_object = OrdQty();
public:
string getClOrdID()
{
return ClOrdID;
}
string getSide()
{
return Side;
}
string getTransactTm()
{
return TransactTm;
}
string getOrdTyp()
{
return OrdTyp;
}
string getPx()
{
return Px;
}
string getAcct()
{
return Acct;
}
Hdr getHdr_object()
{
return Hdr_object;
}
Instrmt getInstrmt_object()
{
return Instrmt_object;
}
OrdQty getOrdQty_object()
{
return OrdQty_object;
}
void setClOrdID(string ClOrdID)
{
this->ClOrdID = ClOrdID;
}
void setSide(string Side)
{
this->Side = Side;
}
void setTransactTm(string TransactTm)
{
this->TransactTm = TransactTm;
}
void setOrdTyp(string OrdTyp)
{
this->OrdTyp = OrdTyp;
}
void setPx(string Px)
{
this->Px = Px;
}
void setAcct(string Acct)
{
this->Acct = Acct;
}
void setHdr_object(Hdr Hdr_object)
{
this->Hdr_object = Hdr_object;
}
void setInstrmt_object(Instrmt Instrmt_object)
{
this->Instrmt_object = Instrmt_object;
}
void setOrdQty_object(OrdQty OrdQty_object)
{
this->OrdQty_object = OrdQty_object;
}
};
class Hdr {
private:
string Snt = "2001-09-11T09:30:47-05:00";
string PosDup = "N";
string PosRsnd = "N";
string SeqNum = "521";
Sndr Sndr_object = Sndr();
Tgt Tgt_object = Tgt();
public:
string getSnt()
{
return Snt;
}
string getPosDup()
{
return PosDup;
}
string getPosRsnd()
{
return PosRsnd;
}
string getSeqNum()
{
return SeqNum;
}
Sndr getSndr_object()
{
return Sndr_object;
}
Tgt getTgt_object()
{
return Tgt_object;
}
void setSnt(string Snt)
{
this->Snt = Snt;
}
void setPosDup(string PosDup)
{
this->PosDup = PosDup;
}
void setPosRsnd(string PosRsnd)
{
this->PosRsnd = PosRsnd;
}
void setSeqNum(string SeqNum)
{
this->SeqNum = SeqNum;
}
void setSndr_object(Sndr Sndr_object)
{
this->Sndr_object = Sndr_object;
}
void setTgt_object(Tgt Tgt_object)
{
this->Tgt_object = Tgt_object;
}
};
class Sndr {
private:
string ID = "AFUNDMGR";
public:
string getID()
{
return ID;
}
void setID(string ID)
{
this->ID = ID;
}
};
class Tgt {
private:
string ID = "ABROKER";
public:
string getID()
{
return ID;
}
void setID(string ID)
{
this->ID = ID;
}
};
class Instrmt {
private:
string Sym = "IBM";
string ID = "459200101";
string IDSrc = "1";
public:
string getSym()
{
return Sym;
}
string getID()
{
return ID;
}
string getIDSrc()
{
return IDSrc;
}
void setSym(string Sym)
{
this->Sym = Sym;
}
void setID(string ID)
{
this->ID = ID;
}
void setIDSrc(string IDSrc)
{
this->IDSrc = IDSrc;
}
};
class OrdQty {
private:
string Qty = "1000";
public:
string getQty()
{
return Qty;
}
void setQty(string Qty)
{
this->Qty = Qty;
}
};
return 0;
}
All the classes I've declared, whether it's Order, Tgt, Sndr. Whenever I make a new instance of these classes, I get the error "Error: identifier classname is undefined"
Thanks in advance
Try declaring them (a) before you use them, and (b) outside of any function:
#include <iostream>
class Test
{
public:
Test() { std::cout << "Test!" << std::endl; }
};
int main()
{
Test t;
}
Once you finish reordering them based on which classes are used by which, it may end up like this:
class OrdQty {
// ...
};
class Instrmt {
// ...
};
class Sndr {
// ...
};
class Tgt {
// ...
};
class Hdr {
// ...
};
class Order {
// ...
};
class FIXML {
// ...
};
int main()
{
return 0;
}
Once you finish that, you'll find that this line is incorrect:
private: Order Order_object = new Order();
You can't initialize a member of a class like this. You'll need to do this in the constructor, copy constructor, and assignment operator, and then clean it up in the destructor.

C++ undefined symbol

I am creating a C++ console application where I am saving and loading a vector to a file. The file I am saving and loading has a header that has the size of the vector.
Here is my code:
void loadFromFile()
{
ifstream iStream("file.ext", ios::binary);
fileHeader_t fHeader;
iStream.read((char*)&fHeader, sizeof(fileHeader_t));
if (fHeader.magicNumber = 0xDEADBEAF)
{
appointments.resize(fHeader.appointmentCount); iStream.read((char*)&appointments[0], fHeader.appointmentCount * sizeof(appointment));
}
}
void saveToFile()
{
ofstream oStream("file.ext", ios::binary);
fileHeader_t fHeader;
fHeader.magicNumber = 0xDEADBEAF;
fHeader.appointmentCount = appointments.size();
oStream.write((char*)&fHeader, sizeof(fileHeader_t));
oStream.write((char*)&appointments[0], sizeof(appointment) * appointments.size());
}
And here is the header struct:
struct fileHeader_s
{
DWORD magicNumber;
size_t appointmentsCount;
}fileHeader_t;
I am getting the following errors:
E2379 Statement missing ;
E2451 Undefined symbol 'fHeader'
At the following lines:
fileHeader_t fHeader;
Why is this happening, and more importantly, how can I fix it?
Thanks
Update
Here is my full code:
class appointment
{
public:
appointment(string aDate, string aTime, string aType,
string aLocation, string aComments, bool aIsImportant,
string aReminderDate, string aReminderTime)
{
appDate = aDate;
appTime = aTime;
appType = aType;
appLocation = aLocation;
appComments = aComments;
appIsImportant = aIsImportant;
appReminderDate = aReminderDate;
appReminderTime = aReminderTime;
}
void setDate(string aDate)
{
appDate = aDate;
}
void setTime(string aTime)
{
appTime = aTime;
}
void setType(string aType)
{
appType = aType;
}
void setLocation(string aLocation)
{
appLocation = aLocation;
}
void setComments(string aComments)
{
appComments = aComments;
}
void setIsImportant(bool aIsImportant)
{
appIsImportant = aIsImportant;
}
void setReminderDate(string aReminderDate)
{
appReminderDate = aReminderDate;
}
void setReminderTime(string aReminderTime)
{
appReminderTime = aReminderTime;
}
string getDate()
{
return appDate;
}
string getTime()
{
return appTime;
}
string getType()
{
return appType;
}
string getLocation()
{
return appLocation;
}
string getComments()
{
return appComments;
}
bool getIsImportant()
{
return appIsImportant;
}
string getReminderDate()
{
return appReminderDate;
}
string getReminderTime()
{
return appReminderTime;
}
private:
appointment();
string appDate;
string appTime;
string appType;
string appLocation;
string appComments;
bool appIsImportant;
string appReminderDate;
string appReminderTime;
//person owner;
};
class calendar
{
public:
calendar()
{
loadFromFile();
}
~calendar()
{
saveToFile();
}
void createAppointment(string aDate, string aTime, string aType, string aLocation, string aComments, bool aIsImportant, string aReminderDate, string aReminderTime)
{
appointment newAppointment(aDate, aTime, aType, aLocation, aComments, aIsImportant, aReminderDate, aReminderTime);
appointments.push_back(newAppointment);
}
private:
vector<appointment> appointments;
string calCurrentDate;
string calCurrentTime;
void loadFromFile()
{
ifstream iStream("file.ext", ios::binary);
fileHeader_t fHeader;
iStream.read((char*)&fHeader, sizeof(fileHeader_t));
if (fHeader.magicNumber = 0xDEADBEAF)
{
appointments.resize(fHeader.appointmentCount); iStream.read((char*)&appointments[0], fHeader.appointmentCount * sizeof(appointment));
}
}
void saveToFile()
{
ofstream oStream("file.ext", ios::binary);
fileHeader_t fHeader;
fHeader.magicNumber = 0xDEADBEAF;
fHeader.appointmentCount = appointments.size();
oStream.write((char*)&fHeader, sizeof(fileHeader_t));
oStream.write((char*)&appointments[0], sizeof(appointment) * appointments.size());
}
typedef struct fileHeader_s
{
DWORD magicNumber;
size_t appointmentCount;
}fileHeader_t;
};
I am getting the following 2 errors:
[BCC32 Warning] Person.cpp(271): W8060 Possibly incorrect assignment
Full parser context
Person.cpp(245): class calendar
Person.cpp(290): decision to instantiate: void calendar::loadFromFile()
--- Resetting parser context for instantiation...
Person.cpp(267): parsing: void calendar::loadFromFile()
[BCC32 Error] vector(608): E2247 'appointment::appointment()' is not accessible
Full parser context
vector(607): decision to instantiate: void vector >::resize(unsigned int)
--- Resetting parser context for instantiation...
Person.cpp(18): #include c:\program files (x86)\embarcadero\rad studio\9.0\include\dinkumware\vector
vector(8): namespace std
vector(330): class vector<_Ty,_Ax>
vector(607): parsing: void vector >::resize(unsigned int)
Can I please have some help to fix this?
You are missing the typedef keyword in struct definition.
typedef struct fileHeader_s
{
}fileHeader_t;
However, in C++ it is not required for the typedef keyword. In that case, struct name is still fileHeader_s.
I think what you want is a typedef
typedef struct fileHeader_s
{
DWORD magicNumber;
size_t appointmentsCount;
}fileHeader_t;

Class declaration and definitions

Here is my Class code:
class LibItem
{
public:
virtual void PrintDetails() = 0;
void setDetails(string setItemTitle, string setItemAuthor, string setItemReleaseDate, string setItemCopyright, string setItemGenre, string setItemStatus)
{
Title = setItemTitle;
Author = setItemAuthor;
ReleaseDate = setItemReleaseDate;
Copyright = setItemCopyright;
Genre = setItemGenre;
Status = setItemStatus;
}
void setTitle(string TitleName)
{
Title = TitleName;
}
string getTitle()
{
return Title;
}
void setReleaseDate(string date)
{
ReleaseDate = date;
}
string getReleaseDate()
{
return ReleaseDate;
}
void setAuthor(string AuthorName)
{
Author = AuthorName;
}
string getAuthor()
{
return Author;
}
void setCopyright(string CopyrightDetails)
{
Copyright = CopyrightDetails;
}
string getCopyright()
{
return Copyright;
}
void setGenre(string GenreDetails)
{
Genre = GenreDetails;
}
string getGenre()
{
return Genre;
}
void setStatus(string StatusDetails)
{
Status = StatusDetails;
}
string getStatus()
{
return Status;
}
private:
string Title;
string ReleaseDate;
string Author;
string Copyright;
string Genre;
string Status;
};
I am wanting to place this into a .h file and a .cpp file.
Is the below code correct?
LibItem.cpp:
//---------------------------------------------------------------------------
#pragma hdrstop
#include "LibItem.h"
virtual void LibItem::PrintDetails() = 0;
void LibItem::setDetails(string setItemTitle, string setItemAuthor, string setItemReleaseDate, string setItemCopyright, string setItemGenre, string setItemStatus)
{
Title = setItemTitle;
Author = setItemAuthor;
ReleaseDate = setItemReleaseDate;
Copyright = setItemCopyright;
Genre = setItemGenre;
Status = setItemStatus;
}
void LibItem::setTitle(string TitleName)
{
Title = TitleName;
}
string LibItem::getTitle()
{
return Title;
}
void LibItem::setReleaseDate(string date)
{
ReleaseDate = date;
}
string LibItem::getReleaseDate()
{
return ReleaseDate;
}
void LibItem::setAuthor(string AuthorName)
{
Author = AuthorName;
}
string LibItem::getAuthor()
{
return Author;
}
void LibItem::setCopyright(string CopyrightDetails)
{
Copyright = CopyrightDetails;
}
string LibItem::getCopyright()
{
return Copyright;
}
void LibItem::setGenre(string GenreDetails)
{
Genre = GenreDetails;
}
string LibItem::getGenre()
{
return Genre;
}
void LibItem::setStatus(string StatusDetails)
{
Status = StatusDetails;
}
string LibItem::getStatus()
{
return Status;
}
};
//---------------------------------------------------------------------------
#pragma package(smart_init)
LibItem.h
//---------------------------------------------------------------------------
#ifndef LibItemH
#define LibItemH
class LibItem
{
public:
virtual void PrintDetails();
void setDetails(string, string, string, string, string, string);
void setTitle(string);
void setReleaseDate(string);
string getReleaseDate();
void setAuthor(string);
string getAuthor();
void setCopyright(string);
string getCopyright();
void setGenre(string);
string getGenre();
void setStatus(string);
string getStatus();
private:
string Title;
string ReleaseDate;
string Author;
string Copyright;
string Genre;
string Status;
};
//---------------------------------------------------------------------------
#endif
Next, if I am wanting to use this .h and .cpp file in a main function, what is the code needed to be able to do this? What are the include statements needed?
Not correct:
virtual void LibItem::PrintDetails() = 0;
The =0 should be inside the class definition (in the header).
To use the class, you need to #include "LibItem.h".
Also, in the header:
#include <string>
and replace occurences of string with std::string.
string parameters should be passed by reference:
void setReleaseDate(const string& date)
instead of
void setReleaseDate(string date)