Hello I do a shopping list. I have a class Customer and a class Item. My program work like this, I ask the name of the customer if the customer isn't in the database I add this customer, and if the customer is I print an error in order to say that the customer exists. After that I print a list of 10 products, and ask the customer to choose a product and increase the count of the specific Item for this customer.
My program don't give any error, I try do debug but I don't find the error, because the program doesn't increase the count of anything.
This is my function in my main:
void DisplayList(Item shopList[10], Customer& custom)
{
int choose_item = 1;
while (choose_item != 0)
{
cout << "The items you can buy are: (0 to exit)" << endl;
for (int i = 0; i < 10; i++)
{
cout << i + 1 << ". " << shopList[i].getName() << " " << shopList[i].getUnitPrice() << " x" << shopList[i].getCount() << endl;
}
cout << "What item you would like to buy, Input: ";
cin >> choose_item;
custom.addItem(shopList[choose_item - 1]);
}
}
My customer header:
class Customer
{
public:
Customer(string);
Customer(){}
void addItem(Item);
set<Item> getItems() const;
private:
string _name;
set<Item> _items;
};
My customer cpp
Customer::Customer(string name)
{
_name = name;
}
Customer::Customer(){ };
void Customer::addItem(Item SpecificItem)
{
set<Item>::iterator it;
if ((it = _items.find(SpecificItem)) != _items.end())
{
SpecificItem.setCount(SpecificItem.getCount() + 1);
}
else
{
_items.insert(SpecificItem);
}
}
set<Item> Customer::getItems() const
{
return _items;
}
My item header:
class Item
{
public:
Item(string, string, double);
~Item();
//get and set functions
string getName() const;
string getSerialNumber() const;
int getCount();
double getUnitPrice() const;
void setCount(int count);
private:
string _name;
string _serialNumber; //consists of 5 numbers
int _count; //default is 1, can never be less than 1!
double _unitPrice; //always bigger than 0!
};
My item cpp
#include "Item.h"
Item::Item(string name, string serial_number, double price) : _name(name), _serialNumber(serial_number), _unitPrice(price), _count(1)
{
};
Item::~Item(){};
string Item::getName() const
{
return _name;
}
string Item::getSerialNumber() const
{
return _serialNumber;
}
int Item::getCount()
{
return _count;
}
double Item::getUnitPrice() const
{
return _unitPrice;
}
void Item::setCount(int count)
{
_count = count;
}
Related
In my function 'func' i want to create an object Menu who returns a breakfast with lemon and coffee. 'func' return a list of menu
When I try to display the menu for a breakfast that contains only lemon or only coffee it is displayed correctly. For example:
c.push_back(make_unique<Breakfast>("eggs", 10));
but when i try to display a menu that also contains lemon and coffee it shows me error in main
this is the program:
#include <iostream>
#include <vector>
using namespace std;
class Menu {
private:
int price;
public:
Menu(int p = 0) : price{ p } {}
virtual string description() = 0;
virtual int getPrice() {
return price;
}
virtual ~Menu() {}
};
class WithLemon : public Menu {
private:
Menu* meniu;
public:
WithLemon(Menu* n) :
meniu{ n } {}
string description() override {
return meniu->description() + " with lemon ";
}
int getPrice() override {
return meniu->getPrice() + 4;
}
};
class WithCoffee : public Menu {
private:
Menu* meniu;
public:
WithCoffee(Menu* n) :
meniu{ n } {
}
string description() override {
return meniu->description() + " with coffee ";
}
int getPrice() override {
return meniu->getPrice() + 5;
}
};
class Breakfast : public Menu {
private:
string name;
public:
Breakfast(string n, int p) :
name{ n }, Menu{ p } {
}
string description() override {
return name;
}
};
std::vector<std::unique_ptr<Menu>> func(void)
{
std::vector <std::unique_ptr<Menu> > c;
Breakfast a{ "breakfast eggs", 10 };
WithCoffee breakfast_with_coffee{ &a };
Menu* breakfast_with_coffee_and_lemon = new WithLemon{ &breakfast_with_coffee };
//cout << breakfast_with_coffee_and_lemon->description() << " " << breakfast_with_coffee_and_lemon->getPrice();// print ----> breakfast eggs with coffee with lemon 19
c.push_back(make_unique<WithLemon>(&breakfast_with_coffee));
return c;
}
int main() {
std::vector < std::unique_ptr<Menu> > lista = func();
for (int i = 0; i < lista.size(); i++) {
cout << lista[i]->description() << " " << lista[i]->getPrice() << endl; //error read memory access
}
return 0;
}
You can't take a pointer to automatic memory, store it in a smart pointer and leave the function. After you leave the function the automatic memory is freed and the smart pointer contains a dangling pointer. The simplest way to avoid this problem and other problems with memory leaks is to use smart pointers for all variables:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Menu {
private:
int price;
public:
Menu(int p = 0) : price{ p } {}
virtual std::string description() = 0;
virtual int getPrice() {
return price;
}
virtual ~Menu() = default;
};
class WithLemon : public Menu {
private:
std::unique_ptr<Menu> meniu;
public:
WithLemon(Menu* n) : meniu{ n } {}
std::string description() override {
return meniu->description() + " with lemon ";
}
int getPrice() override {
return meniu->getPrice() + 4;
}
};
class WithCoffee : public Menu {
private:
std::unique_ptr<Menu> meniu;
public:
WithCoffee(Menu* n) :
meniu{ n } {
}
std::string description() override {
return meniu->description() + " with coffee ";
}
int getPrice() override {
return meniu->getPrice() + 5;
}
};
class Breakfast : public Menu {
private:
std::string name;
public:
Breakfast(std::string n, int p) : Menu{ p }, name{ n } {}
std::string description() override {
return name;
}
};
std::vector<std::unique_ptr<Menu>> func(void) {
std::vector <std::unique_ptr<Menu> > c;
auto a = std::make_unique<Breakfast>("breakfast eggs", 10);
auto breakfast_with_coffee = std::make_unique<WithCoffee>(a.release());
//Menu* breakfast_with_coffee_and_lemon = new WithLemon{ breakfast_with_coffee };
//std::cout << breakfast_with_coffee_and_lemon->description() << " " << breakfast_with_coffee_and_lemon->getPrice();// print ----> breakfast eggs with coffee with lemon 19
c.push_back(std::make_unique<WithLemon>(breakfast_with_coffee.release()));
return c;
}
int main() {
std::vector < std::unique_ptr<Menu> > lista = func();
for (const auto &i : lista) {
std::cout << i->description() << " " << i->getPrice() << std::endl; //error read memory access
}
return 0;
}
Avoid raw new and delete. Avoid pointers to automatic memory.
Hi I'm quite new to c++ and I have a project but to do but a question in the project requires me to add a function, getAverageCostPerDay(), which takes a vector of Reservations object and returns the average cost of a car reservation. How do I got about doing this? Thanks
Reservation.h
#pragma once
#include <string>
class Reservation
{
private:
int id;
std::string name;
int stDate;
int stMonth;
int stYear;
int duration;
float cost;
std::string licensePlate;
static int reservationCount;
public:
//Constructor
Reservation();
Reservation(int id, std::string name, int stDate, int stMonth, int
stYear, int duration, float cost, std::string licensePlate);
//Destructor
~Reservation();
//Getters
int getId();
std::string getName();
int getStDate();
int getStMonth();
int getStYear();
int getDuration();
float getCost();
std::string getLicensePlate();
//Setters
void setId(int id);
void setName(std::string name);
void setStDate(int stDate);
void setStMonth(int stMonth);
void setStYear(int stYear);
void setDuration(int duration);
void setCost(float cost);
void setLicensePlate(std::string licensePlate);
static int getReservationCount()
{
return reservationCount;
}
};
Reservation.cpp
#include "pch.h"
#include "Reservation.h"
int Reservation::reservationCount = 0;
//Constructor
Reservation::Reservation()
{
this->id = 0;
this->name = "";
this->stDate = 0;
this->stMonth = 0;
this->stYear = 0;
this->duration = 0;
this->cost = 0;
this->licensePlate = "";
reservationCount++;
}
Reservation::Reservation(int id, std::string name, int stDate, int stMonth,
int stYear, int duration, float cost, std::string licensePlate)
{
this->id = id;
this->name = name;
this->stDate = stDate;
this->stMonth = stMonth;
this->stYear = stYear;
this->duration = duration;
this->cost = cost;
this->licensePlate = licensePlate;
reservationCount++;
}
//Destructor
Reservation::~Reservation()
{
reservationCount--;
std::cout << "Destroying (" << this->name << ")" << std::endl;
}
//Getters
int Reservation::getId()
{
return this->id;
}
std::string Reservation::getName()
{
return this->name;
}
int Reservation::getStDate()
{
return this->stDate;
}
int Reservation::getStMonth()
{
return this->stMonth;
}
int Reservation::getStYear()
{
return this->stYear;
}
int Reservation::getDuration()
{
return this->duration;
}
float Reservation::getCost()
{
return this->cost;
}
std::string Reservation::getLicensePlate()
{
return this->licensePlate;
}
//Setters
void Reservation::setId(int id)
{
this->id = id;
}
void Reservation::setName(std::string name)
{
this->name = name;
}
void Reservation::setStDate(int stDate)
{
this->stDate = stDate;
}
void Reservation::setStMonth(int stMonth)
{
this->stMonth = stMonth;
}
void Reservation::setStYear(int stYear)
{
this->stYear = stYear;
}
void Reservation::setDuration(int duration)
{
this->duration = duration;
}
void Reservation::setCost(float cost)
{
this->cost = cost;
}
void Reservation::setLicensePlate(std::string licensePlate)
{
this->licensePlate = licensePlate;
}
Main.cpp
#include "pch.h"
#include "Reservation.h"
//Regular Expressions
std::string idRegexStr = "[0-9]{3,4}";
std::string nameRegexStr = "[A-Za-z]{1}[a-z]{1,30} [A-Za-z]{1}[a-z]{1,30}";
std::string stDateRegexStr = "[0-3]{1}[0-9]{1}";
std::string stMonthRegexStr = "[0-1]{1}[0-9]{1}";
std::string stYearRegexStr = "[1-2]{1}[0-9]{1}[0-9]{1}[0-9]{1}";
std::string durationRegexStr = "[1-9]{1}[0-9]{1}";
std::string costRegexStr = "[0-9]{2}.[0-9]{2}";
std::string licencePlateRegexStr = "[0-9]{2,3}\\s*[A-Z]{2,3}\\s*[0-9]+";
//Validates data against a user-defined string
bool validate(std::string regexStr, std::string data)
{
return std::regex_match(data, std::regex(regexStr));
}
std::vector<Reservation>populateVector(Reservation defaultVector, int size)
{
std::vector<Reservation> outVector;
for (int i = 0; i < size; i++)
{
outVector.push_back(defaultVector);
}
return outVector;
}
double getAverageCostPerDay(const std::vector<Reservation> outVector)
{
double average = 0;
for (std::size_t i = 0; i < outVector.size(); i++)
{
average = std::vector<Reservation>outVector.at(float cost);
}
return true;
}
int main()
{
/*
//these were example values to see if regex works
bool idIsValid = validate(idRegexStr, "101");
bool nameIsValid = validate(nameRegexStr, "John Smith");
bool stDateIsValid = validate(stDateRegexStr, "24");
bool stMonthIsValid = validate(stMonthRegexStr, "10");
bool stYearIsValid = validate(stYearRegexStr, "2018");
bool durationIsValid = validate(durationRegexStr, "10");
bool costIsValid = validate(costRegexStr, "22.50");
bool licenseIsValid = validate(licencePlateRegexStr, "181 LH 555");
std::cout << "Invalid = 0 / Valid = 1\n";
std::cout << "\n";
std::cout << "Valid ID: " << idIsValid << std::endl;
std::cout << "Valid Name: " << nameIsValid << std::endl;
std::cout << "Valid Start Date: " << stDateIsValid << std::endl;
std::cout << "Valid Start Month: " << stMonthIsValid << std::endl;
std::cout << "Valid Start Year: " << stYearIsValid << std::endl;
std::cout << "Valid Duration: " << durationIsValid << std::endl;
std::cout << "Valid Cost: " << costIsValid << std::endl;
std::cout << "Valid License: " << licenseIsValid << std::endl;
*/
Reservation r1(101, "John Smith", 24, 10, 2018, 4, 22.50, "181 LH
5555");
Reservation r2(102, "Jane Caroll", 31, 01, 2017, 6, 34.25, "161 DUB
55454");
Reservation r3(103, "Sean Morrissey", 16, 06, 2014, 2, 67.50, "162 WEX
83675");
Reservation r4(104, "Billy Joe", 04, 03, 2016, 8, 51.20, "152 DUB
10347");
std::cout << "Reservation Count: " << Reservation::getReservationCount()
<<
std::endl;
}
There are a couple of ways to do this.
You could wrap your vector of reservations inside of a class and keep track of how many there are, what the total cost is, and calculate the average.
However, if you have to return this information through the Reservation class, then you'll have to use a static variable for sum of costs and number of reservation objects. Static attributes are available in all objects of that class and will have the same value between all objects. So, every time you create a Reservation object, increment the count and sum of costs. Then when you need the average, you can calculate it from any of the objects or through the class (if you make a static function to do this).
I need to write the name, act# balance and address of the object that is stored in the vector, to a file.
I believe I have the program to push the objects into the vectors, but since they are vectors of object pointers I am having problems figure out how to call the object and print all 3 objects out.
Main.cpp
vector<Account*> accounts;
accounts.push_back(new Savings(new Person("Bilbo Baggins", "43 Bag End"), 1, 500, 0.075));
accounts.push_back(new Checking(new Person("Wizard Gandalf", "Crystal Palace"), 2, 1000.00, 2.00));
accounts.push_back(new Savings(new Person("Elf Elrond", "Rivendell"), 3, 1200, 0.050));
ofstream outFile;
outFile.open("accounts.txt");
if (outFile.fail())
{
cout << "\nYour file did not open, the program will now close!\n";
system("PAUSE");
return 0;
}
else
{
cout << "\nBINGO!!! It worked.\n\n";
system("PAUSE");
cout << "\n";
}
// New : Using a loop, send messages to each of the three Account objects to write themselves out to the file.
cout << "\nNow we are going to write the information to \"Accounts.txt\" \n\n";
system("PAUSE");
for (int i = 0; i < accounts.size(); i++) {
accounts[i]->writeAccount(outFile);
}
Account.h
#pragma once
#include <string>
#include <iostream>
#include "Person.h"
using namespace std;
// Account class - abstract/parent class
class Account
{
private:
int actNumber;
double actBallance;
Person PersonName;
public:
Account();
Account(int, double, Person*);
int getActNumber();
virtual double getActBallance();
string getName();
string getAdd();
void deposit(double);
void withdrawl(double);
virtual void writeAccount(ofstream&);
virtual void readAccount(ifstream&);
void testAccount(int i);
};
// Checking class: inherits from the Account class
class Checking : public Account
{
private:
double monthlyFee;
public:
Checking();
Checking(Person*, int, double, double);
void setMonthlyFee(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
// Savings class: inherits from the Account class
class Savings : public Account
{
private:
int interestRate;
public:
Savings();
Savings(Person*, int, double, double); // person, act#, Ballance, Interest Rate
void setInterestRate(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
Account.cpp
#include "Account.h"
#include <string>
using namespace std;
Account::Account()
{
actNumber = 0;
actBallance = 0.0;
}
Account::Account(int act, double bal, Person* name)
{
actNumber = act;
actBallance = bal;
}
int Account::getActNumber()
{
return actNumber;
}
double Account::getActBallance()
{
return actBallance;
}
string Account::getName()
{
return PersonName.getName();
}
string Account::getAdd()
{
return PersonName.getAddress();
}
void Account::deposit(double money)
{
actBallance += money;
}
void Account::withdrawl(double money)
{
actBallance -= money;
}
void Account::writeAccount(ofstream& output)
{
output << actNumber << "\n" << actBallance << "\n" << PersonName.getName() << "\n" << PersonName.getAddress() << endl;
}
void Account::readAccount(ifstream& output)
{
output >> actNumber;
output >> actBallance;
}
// Checking Account
Checking::Checking() {
monthlyFee = 0;
}
Checking::Checking(Person* per, int actNum, double bal, double interest) {
bal -= monthlyFee;
Account:Account(actNum, bal, per);
}
void Checking::setMonthlyFee(double fee) {
monthlyFee = fee;
}
double Checking::getActBallance() {
double ballance = Account::getActBallance();
return ballance = monthlyFee;
}
void Checking::readAccount(ifstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance() - monthlyFee;
output >> actNumber;
output >> actBallance;
}
void Checking::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
// Savings Account
Savings::Savings() {
interestRate = 0;
}
// Savings(Person, int, double, double) // person, act#, Ballance, Interest Rate
Savings::Savings(Person* per, int actNum, double bal, double interest) {
bal += (bal * interest);
Account:Account(actNum, bal, per);
}
void Savings::setInterestRate(double rate) {
interestRate = rate;
}
double Savings::getActBallance() {
double ballance = Account::getActBallance();
return ballance + (ballance * interestRate);
}
void Savings::readAccount(ifstream& output) {
double actBallance = Account::getActBallance();
int actNumber = Account::getActNumber();
actBallance += (actBallance * interestRate);
output >> actNumber;
output >> actBallance;
}
void Savings::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
I realize I am so far off... but I have been at this for HOURS and I can not figure out for the life of me, but to take the vector of object pointers and output the objects values.
Person.h
#pragma once
#include <string>
#include <fstream>
using namespace std;
class Person
{
private:
string name;
string address;
public:
Person();
Person(string a, string b);
string getName();
string getAddress();
void writePerson(ofstream&);
void readPerson(ifstream&);
};
Person.cpp
#include "Person.h"
#include <string>
using namespace std;
Person::Person()
{
name = "NAME";
address = "123 STREET";
}
Person::Person(string a, string b)
{
name = a;
address = b;
}
string Person::getName()
{
return name;
}
string Person::getAddress()
{
return address;
}
void Person::writePerson(ofstream& output)
{
output << name << " " << address << endl;
}
void Person::readPerson(ifstream& output)
{
output >> name;
output >> address;
Person(name, address);
}
Read again your course books on constructors: there are severe issues in all of your constructors. As a result, you don't initialize the object member variables, and you effectively end up printing lots of zeros and empty strings...
Firstly, for your base-class, you must initialize the person name. You should have written:
Account::Account(int act, double bal, Person* name)
: actNumber(act)
, actBallance(bal)
, PersonName(name)
{}
Secondly, for your derived classes, the initialisation of the base-class must be done in the initializer-list, not in the body of the ctor. Here is for exemple the correct definition for the Checking's ctor:
Checking::Checking(Person* per, int actNum, double bal, double interest)
: Account(actNum, bal, per)
, monthlyFee(-bal)
{}
Thirdly, be careful to initialize the member variables with the arguments of the ctor. You sometimes do the opposite and assign the ctor arguments with the (uninitialized) member variables.
BTW, Account is a base-class for a polymorphic hierarchy: thus, the Account destructor must be declared virtual.
I'm attempting to make my class do the following...
EmployeeHandler: Initializes m_employeeCount to zero.
AddEmployee: Invoked by menu option 1. Displays "NEW EMPLOYEE". Prompts the user for
the employee’s first name, last name, and pay rate, one at a time. Uses Employee.Setup to add
an employee to m_lstEmployee. Displays "Employee m_employeeCount added". Increments
m_employeeCount.
EmployeeSelection: Displays the list of employees, by index; prompts the user for an employee
index and returns the index.
EditEmployee: Invoked by menu option 2. Uses EmployeeSelection to get the index of the
employee to edit. Verifies if the index is valid and displays an error message if it is not. Uses
Employee.Output to display the selected employee’s current information. Prompts the user for
the employee’s new first name, last name, and pay rate, one at a time. Uses Employee.Setup to
change the employee’s information in m_lstEmployee. Displays “** Employee index updated”,
where index is the user selected index.
LayoffEmployee: Invoked by menu option 3. Uses EmployeeSelection to get the index of the
employee to lay-off. Uses Employee.Output to display the selected employee’s first name, last
name, and pay rate. Uses Employee.LayOff to lay the employee off. Displays "Employee
index laid off", where index is laid off employee’s index.
DisplayEmployeeList: Invoked by menu option 4. Displays "EMPLOYEES". Then uses
Employee.Output to display every employee record something like this, "[1] David Johnson,
PAY: $5.00 (CURRENT EMPLOYEE)" and a former employee record something like this, "[2]
David Johnson, PAY: $5.00 (FORMER EMPLOYEE)", where the number in the brackets is the
employee’s index in m_lstEmployee.
GetEmployee: Returns the address of the selected employee record in m_lstEmployee.
GetEmployeeCount: Returns the number of employees in m_employeeCount.
So far I have...
#ifndef _EMPLOYEEHANDLER
#define _EMPLOYEEHANDLER
#include "Employee.h"
class EmployeeHandler
{
public:
EmployeeHandler()
{
m_employeeCount = 0; //undefined?
};
void AddEmployee()
{
string firstName;
string lastName;
float payRate;
cout<<"NEW EMPLOYEE"<<endl;
cout<<"First Name:"<<endl;
cin>>firstName;
cout<<"Last Name:"<<endl;
cin>>lastName;
cout<<"Pay Rate:"<<endl;
cin>>payRate;
Employee.Setup(firstName,lastName,payRate); //Problem here
cout<<"**Employee m_employeeCount added"<<endl;
m_employeeCount+=1; //m_employeeCount undefined?
}
void EditEmployee()
{
int indexEdit;
string newFirst;
string newLast;
float newPay;
cout<<"Which employee would you like to edit"<<endl;
cin>>indexEdit;
EmployeeSelection(indexEdit); //undefined?
Employee.Output(); //
cout<<"Employee new first name:"<<endl;
cin>>newFirst;
cout<<"Employee new last name:"<<endl;
cin>>newLast;
cout<<"Employee new pay rate:"<<endl;
cin>>newPay;
Employee.Setup(newFirst,newLast,newPay); ///
cout<<"** Employee index updated"<<endl;
}
void LayoffEmployee()
{
EmployeeSelection();
Employee.Output(EmployeeSelection); //Problems here
Employee.LayOff(EmployeeSelection);
cout<<"Employee laid off"<<endl;
}
void DisplayEmployeeList()
{
cout<<"EMPLOYEES"<<endl;
for (int i=0; i<50; i++)
cout<<[i]<<Employee.Output(m_1stEmployee)<<endl; //
}
int EmployeeSelection()
{
int indexNumber;
for (int i= 0; i <50; i++)
cout<<[i]m_1stEmployee<<endl; //
cout<<"Which Employee Index would you like to select?"<<endl;
cin>>indexNumber;
for (int i = 0; i <50; i++)
if ([i]=indexNumber) //
return [i]
}
Employee& GetEmployee( int index )
{if (index=; // completely confused here
}
int GetEmployeeCount()
{
return m_employeeCount;
};
private:
Employee m_lstEmployee[50];
int m_employeeCount;
};
#endif
The employee.h file is as follows...
#ifndef _EMPLOYEE
#define _EMPLOYEE
#include<iostream>
#include<iomanip>
#include <string>
using namespace std;
class Employee
{
public:
void Setup( const string& first, const string& last, float pay );
{
m_firstName = first;
m_lastName = last;
m_payPerHour = pay;
m_activeEmployee = true;
}
string GetName()
{
return m_firstName+""+m_lastName
};
bool GetIsActive()
{
return m_activeEmployee;
};
void LayOff()
{
m_activeEmployee= false;
};
void Output()
cout<<GetName()<<",PAY:$"<<fixed<<setprecision(2)<<m_payPerHour<<endl;
private:
string m_firstName;
string m_lastName;
float m_payPerHour;
bool m_activeEmployee;
};
#endif
I've been stuck writing this class for the last two days trying to figure out what I'm doing wrong. This is the first time I've attempted to write classes in C++. Any and all help is much, much appreciated. I have marked places where I'm having problems with //.
Your code has many, many problems...
I'll start by providing compilable code that more or less does what you want. I'm not sure how you can go about asking questions, but compare it to your own code and read a good c++ book...
I've replaced your array with a vector. I've used a constructor to initialize Employee. I've (to my own dismay) added std, mainly because Employee shall live in its own header and it's not good to use a namespace in a header.
In c++ the operator[] is postfix (after the indexed expression).
Also, under normal circumstances I'll try and keep interface and implementation seperate where possible. At the least I would not use inline functions if not absolutely necessary.
The new code...:
#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <string>
class Employee
{
public:
//This is a constructor....
Employee( const std::string& first, const std::string& last, float pay )
//The members can be initialized in a constructor initializer list as below.
: m_firstName( first ), m_lastName( last ), m_payPerHour( pay ),
m_activeEmployee() //Scalars are initialized to zero - bool to false...
{
}
std::string GetName() const
{
return m_firstName+" "+m_lastName;
}
bool GetIsActive() const
{
return m_activeEmployee;
};
void LayOff()
{
m_activeEmployee = false;
}
std::ostream& Output( std::ostream& out ) const
{
return out << GetName() <<",PAY:$"
<< std::fixed << std::setprecision(2) << m_payPerHour;
}
private:
std::string m_firstName;
std::string m_lastName;
float m_payPerHour;
bool m_activeEmployee;
};
inline std::ostream& operator << ( std::ostream& os, const Employee& employee )
{
return( employee.Output( os ) );
}
class EmployeeHandler
{
public:
void AddEmployee()
{
std::string firstName;
std::string lastName;
float payRate;
std::cout<<"NEW EMPLOYEE"<<std::endl;
std::cout<<"First Name:"<<std::endl;
std::cin>>firstName;
std::cout<<"Last Name:"<<std::endl;
std::cin>>lastName;
std::cout<<"Pay Rate:"<<std::endl;
std::cin>>payRate;
employees_.push_back( Employee( firstName,lastName,payRate ) );
std::cout<<"**Employee m_employeeCount added"<<std::endl;
}
void EditEmployee()
{
std::string newFirst;
std::string newLast;
float newPay;
std::cout<<"Which employee would you like to edit"<<std::endl;
int indexEdit = GetSelection();
Employee& employee = employees_[indexEdit];
std::cout << employee << std::endl;
std::cout<<"Employee new first name:"<<std::endl;
std::cin>>newFirst;
std::cout<<"Employee new last name:"<<std::endl;
std::cin>>newLast;
std::cout<<"Employee new pay rate:"<<std::endl;
std::cin>>newPay;
employee = Employee( newFirst, newLast, newPay );
std::cout<<"** Employee index updated"<<std::endl;
}
void LayoffEmployee()
{
int index = GetSelection();
if( employees_[index].GetIsActive() )
{
std::cout << "Laying off employee:\n" << employees_[index] << std::endl;
employees_[index].LayOff();
}
else
{
std::cerr << "Already layed off employee:" << employees_[index] << std::endl;
}
}
void DisplayEmployeeList()
{
std::copy( employees_.begin(), employees_.end(), std::ostream_iterator<Employee>( std::cout, "\n" ) );
}
int GetSelection()
{
std::size_t indexNumber;
std::cout << "Select an employee from the list below by specifying its number:" << std::endl;
DisplayEmployeeList();
do{
while( !std::cin >> indexNumber )
{
std::cin.clear();
std::cin.ignore();
std::cerr << "Select a number..." << std::endl;
}
if( indexNumber >= employees_.size() )
{
std::cerr << "Select a number within range of list below:" << std::endl;
DisplayEmployeeList();
}
}
while( indexNumber >= employees_.size() );
return indexNumber;
}
Employee& operator[]( std::size_t index )
{
return employees_[index];
}
const Employee& operator[]( std::size_t index ) const
{
return employees_[index];
}
std::size_t EmployeeCount() const
{
return employees_.size();
}
private:
std::vector<Employee> employees_;
};
int main( int argc, char* argv[] )
{
return 0;
}
Finally - the code is merely compiled, not tested. I suspect I might have made a mistake, but alas, time!!!
i am new to C++ and stuck in the swap stuff
the code below is a program of sort employee names in alphbetical order and print out the orginal one and sorted one ,but the
swap method doesn't work
the two output of printEmployees is excatly the same, can anyone help me? thx
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;
class employee
{
/* Employee class to contain employee data
*/
private:
string surname;
double hourlyRate;
int empNumber;
public:
employee() {
hourlyRate = -1;
empNumber = -1;
surname = "";
}
employee(const employee &other) :
surname(other.surname),
hourlyRate(other.hourlyRate),
empNumber(other.empNumber){}
void setEmployee(const string &name, double rate,int num);
string getSurname() const;
void printEmployee() const;
employee& operator = (const employee &other)
{employee temp(other);
return *this;}};
void employee::setEmployee(const string &name, double rate, int num) {
surname = name;
hourlyRate = rate;
empNumber = num;
}
string employee::getSurname() const { return surname; }
void employee::printEmployee() const {
cout << fixed;
cout << setw(20) << surname << setw(4) << empNumber << " " << hourlyRate << "\n";
}
void printEmployees(employee employees[], int number)
{
int i;
for (i=0; i<number; i++) { employees[i].printEmployee(); }
cout << "\n";
}
void swap(employee employees[], int a, int b)
{
employee temp(employees[a]);
employees[a] = employees[b];
employees[b] = temp;
}
void sortEmployees(employee employees[], int number)
{
/* use selection sort to order employees,
in employee
name order
*/
int inner, outer, max;
for (outer=number-1; outer>0; outer--)
{
// run though array number of times
max = 0;
for (inner=1;
inner<=outer; inner++)
{
// find alphabeticaly largest surname in section of array
if (employees
[inner].getSurname() < employees[max].getSurname())
max = inner;
}
if (max != outer)
{
//
swap largest with last element looked at in array
swap(employees, max, outer);
}
}
}
int main()
{
employee employees[5];
employees[0].setEmployee("Stone", 35.75, 053);
employees[1].setEmployee
("Rubble", 12, 163);
employees[2].setEmployee("Flintstone", 15.75, 97);
employees[3].setEmployee("Pebble", 10.25, 104);
employees[4].setEmployee("Rockwall", 22.75, 15);
printEmployees(employees, 5);
sortEmployees(employees,5);
printEmployees(employees, 5);
return 0;
}
This code is broken:
employee& operator = (const employee &other)
{employee temp(other);
return *this;}
It should be something like:
employee& operator= (const employee &other)
{
surname = other.surname;
hourlyRate = other.hourlyRate;
empNumber = other.empNumber;
return *this;
}
As told by others, fixing your assignment operator will solve the problem.
I see that you tried to implement operator= in terms of copy constructor but missed to do a swap. You can try the below approach if you want to avoid code duplication in your copy constructor and assignment operator.
employee& operator=(const employee& other)
{
employee temp(other);
swap(temp);
return *this;
}
void swap(employee& other)
{
std::swap(surname, other.surname);
std::swap(hourlyRate, other.hourlyRate);
std::swap(empNumber, other.empNumber);
}