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!!!
Related
I am new programming and C++. I am trying to create a Roster of Person objects using an array and then printing the attributes of the People in the Roster.
When I attempt to add a Person to the personArray, I am getting an
Exception = EXC_BAD_ACCESS (code=1, address=0x0).
I think this has to do with the scope of my personArray but I can't seem to figure it out.
Here is the code I am using:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class Person
{
public:
Person(string name, int age);
string getName() {
return name;
}
void setName(string n) {
name = n;
}
int getAge() {
return age;
}
void setAge(int a) {
age = a;
}
private:
string name;
int age;
};
class Roster {
public:
void addToPersonArray(string name, string age) {
Person person(name, stoi(age));
personArray[personCount] = &person;
}
void printPersonArray() {
for (int i = 0; i < 5; i++)
cout << personArray[i]->getName() << '\t' << personArray[i]->getAge() << '\n';
}
private:
Person *personArray[5];
int personCount = 0;
};
int main() {
const string studentData[] = {"Dan,45", "Mark,33", "Mary,22",
"April,17", "Jill,22"};
Roster roster;
stringstream ss(studentData[0]); // just testing the first entry
vector<string> result;
while (ss.good()) {
string substr;
getline(ss, substr, ',');
result.push_back(substr);
}
roster.printPersonArray();
}
The problem is here:
void addToPersonArray(string name, string age) {
Person person(name, stoi(age));
personArray[personCount] = &person;
}
person is a local variable in the member function addToPersonArray(), which will be destroyed after the function scope.
Hence, storing the address of a local variable(and trying to accessing it latter in printPersonArray()) will give you, nothing but an undefined behavior.
You are lucky that your programme got the exception.
One more thing to note that, you are not actually using your roster to test the program. Instead, all you do is parsing and saving to result vector. You can add this after the while loop, to make it actually work.
if (result.size() == 2) {
roster.addToPersonArray(result[0], result[1]);
}
Suggestion: Since you have a fixed array size, you probably wanna do it with std::array<Person, 5> or with std::vector<Person> by reserving the memory for 5 Person in the c'tor of Roster.
See a sample output: https://wandbox.org/permlink/tAGqqnhCfwz1wPrH
#include <iostream>
#include <sstream>
#include <vector>
#include <array>
class Person {
public:
Person(const std::string& name, int age): name(name), age(age) {}
std::string getName()const { return name; }
void setName(const std::string& n){ name = n; }
int getAge()const { return age; }
void setAge(int a) { age = a; }
private:
std::string name;
int age;
};
class Roster {
public:
Roster() { personArray.reserve(5); } // reserve some memory
void addToPersonArray(const std::string& name, const std::string& age) {
personArray.emplace_back(name, stoi(age));
}
void printPersonArray() {
// use range loop, which will assure, access what you have.
for (const Person& person: personArray)
std::cout << person.getName() << '\t' << person.getAge() << '\n';
}
private:
std::vector<Person> personArray;
//int personCount = 0; --------------> no need anymore
};
int main() {
std::array<std::string,5> studentData{ "Dan,45", "Mark,33", "Mary,22", "April,17", "Jill,22" };
Roster roster;
for(const std::string& str: studentData)
{
std::stringstream ss(str);
std::vector<std::string> result;
while (ss.good()) {
std::string substr;
std::getline(ss, substr, ',');
result.emplace_back(substr);
}
if (result.size() == 2) {
roster.addToPersonArray(result
[0], result[1]);
}
}
roster.printPersonArray();
return 0;
}
Output:
Dan 45
Mark 33
Mary 22
April 17
Jill 22
In addition to storing pointers to local variables in your addToPersonArray() function, your main() function does not add any entries to the personArray.
Instead, main creates a Roster object, and after some code that doesn't affect anything with Roster, you go straight into calling roster.printPersonArray, which does this:
void printPersonArray()
{
for (int i = 0; i < 5; i++) // <-- This will loop for all 5 entries
cout << personArray[i]->getName() << '\t' << personArray[i]->getAge() << '\n';
}
Since personArray was never initialized to contain valid pointers to Person objects, that loop will cause undefined behavior.
The issue is that you have a personCount member variable, but fail to make use of it to control how many valid entries there are in the array. The loop should have been written as below:
void printPersonArray()
{
for (int i = 0; i < personCount; i++)
cout << personArray[i]->getName() << '\t' << personArray[i]->getAge() << '\n';
}
In addition to the storage of pointers to local variables, your Roster::addToPersonArray() doesn't check if personCount is greater than 4, thus this is another place in your code where you failed to use personCount to control how many Person objects are being referenced.
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;
}
I'm just starting to learn object oriented programming in C++ and am having issues figuring out how to print an object that is stored inside an array. From what I know, I want to just try to try and go through the array and print out each employee object, how because objects are different than variables like int and double I'm sure it's causing a problem. Is my logic wrong, or is it just syntax? Here is my code:
Header:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
class Employee
{
private:
string name;
string idNumber;
string department;
string position;
int yearsWorked;
public:
Employee();
Employee(string, string);
Employee(string, string, string, string, int);
void setName(string);
void setIdNumber(string);
void setDepartment(string);
void setPosition(string);
bool setYearsWorked(int);
string getName()const;
string getIdNumber()const;
string getDepartment()const;
string getPosition()const;
int getYearsWorked()const;
};
#endif
Implementation:
#include "Employee.h"
using namespace std;
Employee::Employee()
{
string name = "";
string idNumber = "";
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id)
{
string name = nm;
string idNumber = id;
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id, string dpt, string pos, int years)
{
string name = nm;
string idNumber = id;
string department = dpt;
string position = pos;
int yearsWorked = years;
}
void Employee::setName(string nm)
{
name = nm;
}
void Employee::setIdNumber(string id)
{
idNumber = id;
}
void Employee::setDepartment(string dpt)
{
department = dpt;
}
void Employee::setPosition(string pos)
{
position = pos;
}
bool Employee::setYearsWorked(int years)
{
if (years >= 0)
{
yearsWorked = years;
return true;
}
else
return false;
}
string Employee::getName()const
{
return name;
}
string Employee::getIdNumber()const
{
return idNumber;
}
string Employee::getDepartment()const
{
return department;
}
string Employee::getPosition()const
{
return position;
}
int Employee::getYearsWorked()const
{
return yearsWorked;
}
Main:
#include <iostream>
#include <iomanip>
#include "Employee.h"
using namespace std;
const int SIZE = 3;
int main()
{
Employee emp1("Jenny Jacobs", "JJ8990", "Accounting", "President", 15);
Employee emp2("Myron Smith", "MS7571", "IT", "Programmer", 5);
Employee emp3("Chris Raines", "CR6873", "Manufacturing", "Engineer", 30);
Employee employees[SIZE] = {emp1, emp2, emp3};
for (int i = 0; i < SIZE; i++)
{
cout << employees[i] << endl;
}
system("PAUSE");
return 0;
}
Add this:
std::ostream& operator<<( std::ostream& stream, Employee const& emp )
{
return (stream << emp.getName());
}
Modify as needed.
General comments:
Do not place using namespace std; in the global namespace in a header. Keep in mind that the standard library defines very common names like distance. Which can easily lead to name collisions.
Reserve ALL UPPERCASE names for macros, to reduce the chance of name collisions and inadvertent text substitution.
Preferentially pass potentially "large" objects, such as std::string, by reference, e.g. formal argument type std::string const&, in order to avoid excessive copying. There are some exceptions to this rule when one aims for perfect code, e.g. for C++11 move semantics, but it's a good general rule.
employees[i] is of type Employee. So either you have to print like
cout<<employees[i].getName(); // so on
Or you have to overload << operator for Employee type:
ostream& operator<<(ostream& stream, Employee const& emp );
Firstly. in my machine it compiles fine
Secondly, you are doing:
string name = nm;
So name is a automatic variable, Not the member of your class. You should do like:
name = nm; // if you delete int name; line
Or,
this->name = nm;
Some changes of your code:
Employee::Employee()
: yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), department( dpt ), position( pos ), yearsWorked( years ),
{
}
std::ostream & operator <<( std::ostream &os, const Employee &emp )
{
return ( os << "ID: " << emp.idNumber << ", name: " << emp.name
<< ", department: " << emp.department << ", position: " << emp.position
<< ", years worked: " << emp.yearsWorked );
}
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);
}
I am adding musicCD information to a set. I have two different functions for this. The problem is adding the musicians. Its only adding the last musician being passed in like its copying over the first ones.
here is the required output to give you an idea of the info. Only ringo starr is adding and not "George Harrison" "John Lennon".
-MusicCD-
band: Beatles
musicians: "George Harrison" "John Lennon" "Ringo Starr"
songs: 10
title: Sergeant Pepper's Lonely Hearts Club Band
keywords: acid rock, sixties
here is main()
item = library->addMusicCD("Sergeant Pepper's Lonely Hearts Club Band", "Beatles", 10);
if (item != NULL) {
library->addKeywordForItem(item, "acid rock");
library->addKeywordForItem(item, "sixties");
library->addBandMember(item, "John Lennon");
library->addBandMember(item, "George Harrison");
library->addBandMember(item, "Ringo Starr");
library->printItem(cout, item);
}
here is the libray.h file where i am adding the info
#include "Library.h"
#include "book.h"
#include "cd.h"
#include "dvd.h"
#include <iostream>
// general functions
ItemSet allBooks;
ItemSet allCDS;
ItemSet allDVDs;
ItemSet* temp;
ItemSetMap allBooksByAuthor;
ItemSetMap allmoviesByDirector;
ItemSetMap allmoviesByActor;
ItemSetMap allMusicByBand;
ItemSetMap allMusicByMusician;
const Item* Library::addMusicCD(const string& title, const string& band, const int nSongs)
{
ItemSet* obj = new ItemSet();
CD* item = new CD(title,band,nSongs);
allCDS.insert(item);
obj->insert(item);
//allMusicByBand[band] = obj;
ItemSetMap::iterator myband = allMusicByBand.find(band);
if(myband != allMusicByBand.end())
{
myband->second->insert(item);
}
else{
allMusicByBand.insert(make_pair(band, obj));
}
return item;
}
void Library::addBandMember(const Item* musicCD, const string& member)
{
ItemSet* obj = new ItemSet();
(((CD*) musicCD)->addBandMember(member));
obj->insert((CD*) musicCD);
ItemSetMap::iterator MByMusician = allMusicByMusician.find(member);
if(MByMusician != allMusicByMusician.end())
{
MByMusician->second->insert((CD*) musicCD);
}
else
{
allMusicByMusician.insert(make_pair(member, obj));
}
}
and here is the cd.cpp class
#include "CD.h"
using namespace std;
CD::CD(const string& theTitle, const string& theBand, const int snumber)
: Item(theTitle), band(theBand),number(snumber)
{
}
CD::~CD()
{
}
const string CD::getBand() const
{
return band;
}
const string CD::getMusician() const
{
return musicians;
}
const int CD::getNumber() const
{
return number;
}
void CD::addBandMember(const string &member)
{
this->musicians = member;
}
void CD::print(ostream &out) const
{
out << "-MusicCD-" << endl;
out << "band: " << this->getBand() << endl;
out << "musicians: " << this->getMusician() << endl;
out << "songs: " << this->getNumber() << endl;
out << "title: " << this->getTitle() << endl;
out << "keywords: " << this->printKeywords(this->getKeywords()) << endl;
out << endl;
}
ostream& operator<<(ostream& out, const CD* cd)
{
cd->print(out);
return out;
}
finally, here is the cd.h
#ifndef CD_H
#define CD_H
#pragma once
#include "item.h"
class CD : public Item
{
public:
CD(const string& theTitle, const string& theBand, const int snumber);
void addBandMember(const string& member);
const int getNumber() const;
const string getMusician() const;
const string getBand() const;
virtual void print(ostream& out) const;
~CD();
private:
string band;
string musicians;
string title;
int number;
};
ostream& operator<<(ostream& out, const CD* cd);
#endif
I have to assume my problem lies in the Library::addBandMember function?
Keep in mind i cannot change that function in the library class.
Yes.
string musicians;
This variable stores a single string. Hence, even though the call succeeds for addBandMember it gets overwritten by the next call. Hence, all you are left with is the name of the last added musician -- Ringo in your case. Use a list or vector instead to hold all musicians.
vector<string> musicians;
and modify addBandMember as:
void CD::addBandMember(const string &member)
{
this->musicians.push_back(member);
}
Only ringo starr is adding and not "George Harrison" "John Lennon".
To turn the bug into a feature, rearrange the names so George Harrison is the only one that's added. Then you'll have artificial intelligence so good it has better musical taste than most people!
Seriously though, right now your cd.h has "musicians" as a single string, not a collection of strings. If you want to badly enough, you could put all the musicians in a single string, but at a guess, you'd rather have a vector of strings or something on that order.