Need help implementing istream& operator >> method - c++

I have looked over many questions available on SO, but I could not find something that actually answered my question.
I was wondering how to implement the istream& operator >> method to create an array of Books.
I just need help with the istream method, not the whole program.
#include "Warehouse.h"
#include "Book.h"
#include <iostream>
#include<string>
using namespace std;
static const int MAX_BOOKS = 35;
clss Warehouse {
/**
* #param is the input stream
* #param warehouse the warehouse object reference
* #return the input stream
*/
friend istream& operator >> (istream& is, Warehouse& warehouse);
/**
* #param os the output stream
* #param warehouse the warehouse object reference
* #return the output stream
*/
friend ostream& operator << (ostream& os, const Warehouse& warehouse);
public:
static const int MAX_BOOKS = 35;
Warehouse();
/**
* #param isbn the ISBN number to search for
* #param book reference to the matched book object, if found
* #return true if found.
*/
bool find (string isbn, Book& book) const;
/**
* Prints the inventory of the Warehouse (i.e. list all the books)
*/
void list () const;
private: /* extra credit */
void sort_();
private:
Book books[Warehouse::MAX_BOOKS];
int bookCount;
};
#endif /* WAREHOUSE_H */
This is the cpp file for the Book:
#include "Book.h"
#include <iostream>
#include <string>
using namespace std;
static const int MAX_BOOKS = 35;
static const int MAX_AUTHORS = 20;
string title_;
string authors_[Book::MAX_AUTHORS];
int authorCount_;
string publisher_;
short yearPublish_;
bool hardcover_;
float price_;
string isbn_;
long copies_;
istream& operator >> (istream& is, Book& book){
is >> book.title_;
is.ignore();
is >> book.authorCount_;
for (int j=0;j<book.authorCount_;j++){
is >> book.authors_[j];
is.ignore();
}
is >> book.publisher_;
is.ignore();
is >> book.yearPublish_;
is.ignore();
is >> book.hardcover_;
is.ignore();
is >> book.price_;
is.ignore();
is >> isbn_;
is.ignore();
is >> copies_;
is.ignore();
return is;
}
ostream& operator << (ostream& os, const Book& book){
os<< book.title_ << endl;
for (int j=0; j<book.authorCount_; j++){
os<< book.authors_[j] << endl;
}
os<< book.publisher_ << endl;
os<< book.yearPublish_;
os<<book.hardcover_;
os<< book.price_ << endl;
os<< book.isbn_ << endl;
os<< book.copies_ << endl;
return os;
}
Book :: Book() {};
Book :: Book (string title, string authors[], int authorCount, string publisher, short yearPublish, bool hardcover, float price, string isbn, long copies){
title_ = title;
authorCount_ = authorCount;
for (int i=0;i<authorCount_;i++){
authors_[i] = authors[i];
}
publisher_ = publisher;
yearPublish_ = yearPublish;
hardcover_ = hardcover;
price_ = price;
isbn_ = isbn;
copies_= copies;
}
void Book::setTitle(string title){
title_=title;
}
string Book::getTitle()const{
return title_;
}
void Book:: setAuthorCount(short authorCount){
authorCount_ = authorCount;
}
void Book::setAuthors(string authors[]){
authors_[MAX_AUTHORS]=authors[MAX_AUTHORS];
}
string Book::getAuthors() const{
return authors_[MAX_AUTHORS-1];
}
void Book::setPublisher(string publisher){
publisher_ = publisher;
}
string Book::getPublisher() const{
return publisher_;
}
void Book::setYearPublish(short yearPublish){
yearPublish_ = yearPublish;
}
short Book:: getYearPublish() const{
return yearPublish_;
}
void Book::setHardcover(bool hardcover){
hardcover_ = hardcover;
}
bool Book::getHardcover() const{
return hardcover_;
}
void Book:: setIsbn(string isbn){
isbn_ = isbn;
}
string Book::getIsbn() const{
return isbn_;
}
void Book:: setPrice(float price){
price_ = price;
}
float Book:: getPrice() const{
return price_;
}
void Book:: setCopies(long copies){
copies_ = copies;
}
long Book::getCopies()const{
return copies_;
}

Related

Set and get methods in a class for objects

I have a class Result which takes two other classes UNIT and Date as object parameters, so that I can store the values in them for use in those classes. I will put down what Ive got so far, and a few of the errors I get are as follows.
error: prototype for 'int Result::GetUnit() const' does not match any in class 'Result'|
lab2\Result.h|17|error: candidate is: Result Result::GetUnit() const|
lab2\Result.cpp|66|error: prototype for 'int Result::GetDate()' does not match any in class 'Result'|
lab2\Result.h|18|error: candidate is: Result Result::GetDate() const|
lab2\Result.cpp|73|error: 'SetResult' was not declared in this scope|
error: 'SetResult' was not declared in this scope|
For the error not declared in this scope, after researching I understand that I need to define the functions before the first call is made. I have done that in the .cpp file but I still get the error. What am I doing wrong?
Result.h:
#ifndef RESULT_H
#define RESULT_H
#include <iostream>
#include <string>
#include "UNIT.h"
#include "Date.h"
//const unsigned ResultSize = 10;
using namespace std;
class Result
{
public:
Result(){};
Result(UNIT unitobj1, unsigned marks1, Date dateobj1);
Result GetUnit() const;
Result GetDate() const;
void SetDate(Date dateobj1);
void SetUnit(UNIT unitonj1);
void SetMarks( unsigned marks1 );
unsigned GetMarks() const;
void SetCredits( unsigned cred );
unsigned GetCredits() const;
string GetID() const;
void SetID(string idd);
void SetResult(istream & input);
void GetResult(ostream & os);//unsigned GetUnit() const;
private:
UNIT unitobj;
Date dateobj;
string id;
int credits;
unsigned marks;
};
inline unsigned Result::GetCredits() const
{
return credits;
}
ostream & operator <<( ostream & os, const Result & S);
istream & operator >>( istream & input, Result & S);
#endif // RESULT_H
Result.cpp:
#include "Result.h"
#include "UNIT.h"
#include "Date.h"
Result::Result(UNIT unitobj1, unsigned marks1, Date dateobj1)
{
unitobj = unitobj1;
marks = marks1;
dateobj = dateobj1;
}
void Result::SetResult(istream &input){
UNIT unitobj1;
unsigned marks1;
Date date1;
input >> unitobj1 >> marks1 >> date1;
SetUnit(unitobj1);
SetMarks(marks1);
SetDate(date1);
}
void Result::GetResult(ostream &os){
os << GetUnit() < " Marks: " << GetMarks() << '\n' << GetDate() << '\n';
}
void Result::SetUnit(UNIT unitobj1){
unitobj = unitobj1;
}
void Result::SetMarks(unsigned marks1){
marks = marks1;
}
void Result::SetDate(Date dateobj1){
dateobj = dateobj1;
}
Result::GetUnit() const{
return unitobj;
}
inline unsigned Result::GetMarks() const{
return marks;
}
Result::GetDate(){
return dateobj;
}
istream & operator >>( istream & input, Result & S)
{
SetResult(input);
return input;
}
ostream & operator <<( ostream & os, const Result & S)
{
GetResult(os);
return os;
}
Date.h:
#if !defined(_DATE_H)
#define _DATE_H
#include <iostream>
#include <string>
using namespace std;
class Date {
public:
Date();
Date(unsigned day1, string month1, unsigned year1);
void SetDay(unsigned day1);
void SetMonth(string month1);
void SetYear(unsigned year1);
unsigned GetDay() const;
string GetMonth() const;
unsigned GetYear() const;
void SetDate(istream &input);
void GetDate(ostream & os);
private:
unsigned day;
string month;
unsigned year;
};
ostream & operator <<(ostream & os, const Date & D);
istream & operator >>(istream & input, Date & D);
#endif //_DATE_H
Date.cpp:
//
//
// Generated by StarUML(tm) C++ Add-In
#include "Date.h"
Date::Date(unsigned day1, string month1, unsigned year1) {
day = day1;
month = month1;
year = year1;
}
void Date::SetDay(unsigned day1) {
day = day1;
}
void Date::SetMonth(string month1) {
month = month1;
}
void Date::SetYear(unsigned year1) {
year = year1;
}
inline unsigned Date::GetDay() const {
return day;
}
string Date::GetMonth() const {
return month;
}
inline unsigned Date::GetYear() const {
return year;
}
void Date::SetDate(istream &input){
unsigned day1;
string month1;
unsigned year1;
input >> day1 >> month1 >> year1;
SetDay(day1);
SetMonth(month1);
SetYear(year1);
}
void Date::GetDate(ostream &os){
os << " Date: " << GetDay() << " " << GetMonth() << " " << GetYear();
}
istream & operator >>( istream & input, Date & D) {
SetDate(input);
return input;
}
ostream & operator <<( ostream & os, const Date & D) {
GetDate(os);
return os;
}
UNIT.h:
#ifndef UNIT_H
#define UNIT_H
#include <iostream>
#include <string> // C string library
using namespace std;
const unsigned UnitNameSize = 10;
class UNIT
{
public:
UNIT();
UNIT( string nam, string idd, unsigned cred);
void SetName(string nam);
string GetName() const;
void SetMarks(unsigned marks1);
unsigned GetMarks();
void SetCredits(unsigned cred);
unsigned GetCredits() const;
string GetID() const;
void SetID(string idd);
void SetUnit(istream & input);
void GetUnit(ostream & os);
private:
string name;
string id;
unsigned marks;
int credits;
};
ostream & operator <<( ostream & os, const UNIT & U);
istream & operator >>( istream & input, UNIT & U);
#endif // UNIT_H
UNIT.cpp:
#include "UNIT.h"
#include <string>
UNIT::UNIT()
{
name[0] = '\0';
}
void UNIT::SetName(string nam)
{
name = nam;
}
string UNIT::GetName() const
{
return name;
}
void UNIT::SetID(string idd)
{
id = idd;
}
string UNIT::GetID() const
{
return id;
}
void UNIT::SetCredits(unsigned cred){
credits = cred;
}
inline unsigned UNIT::GetCredits() const{
return credits;
}
UNIT::UNIT( string nam, string idd,
unsigned cred)
{
name.replace(0, 10, nam );
id = idd;
credits = cred;
}
void UNIT::SetUnit(istream &input){
string nam;
string idd;
unsigned cred;
getline(input,nam, '\n');
getline(input,idd,'\n');
input >> cred;
SetName(nam);
SetID(idd);
SetCredits(cred);
}
void UNIT::GetUnit(ostream & os){
os << " Unit ID: " << GetID() << '\n'
<< " Unit Name: " << GetName() << '\n'
<< " Credits: " << GetCredits() << '\n';
}
istream & operator >>( istream & input, UNIT & U)
{
SetUnit(input);
return input;
}
ostream & operator <<( ostream & os, const UNIT & U)
{
GetUnit(os);
return os;
}
Note: I know that I can just make the overloaded operators methods of the class and declare them as friends, but I am trying to achieve this by using set and get methods. Any help would be very appreciated!
So, this is pretty straightforward, look at Result::GetUnit
Result::GetUnit() const {
return unitobj;
}
This method is missing a return type. Now look at unitobj
UNIT unitobj;
So it's clear that the return type should be UNIT, so the above method should be defined as
UINT Result::GetUnit() const {
return unitobj;
}
Now look at how you declared this method in your class
class Result
{
...
Result GetUnit() const;
Here you gave it a return type of Result where we've already seen that the return type should be UINT, so change the above to
class Result
{
...
UNIT GetUnit() const;
Result::GetDate has similar problems, here the return type should be Date but again you specified it as Result.
For the SetResult error you simply need to specify that you are calling the SetResult method on a Result object. The compiler thinks you are calling a global SetResult function (which doesn't exist)
Like this
istream & operator >>( istream & input, Result & S)
{
S.SetResult(input);
return input;
}
S.SetResult(input); tells the compiler that you want to call the SetResult method using the Result object refered to by S.
You can tell this by reading the error message carefully, it said 'SetResult' was not declared in this scope, not 'Result::SetResult' was not declared in this scope. As you said you have declared Result::SetResult, but your code wasn't calling that, it was trying to call a different function called SetResult and the compiler correctly reported that no such function was declared.

How to operate overload ">>"?

Product **products;
int numProducts = 0;
void setup()
{
ifstream finput("products.txt");
//get # of products first.
finput >> numProducts;
products = new Product* [numProducts];
//get product codes, names & prices.
for(int i=0; i<numProducts; i++) {
products[i] = new Product;
finput >> products[i]->getCode() >> products[i]->getName() >> products[i]->getPrice();
}
}
I am getting an "invalid operands to binary expression" error for this line:
finput >> products[i]->getCode() >> products[i]->getName() >> products[i]->getPrice();
Do I need to operator overload >> and how would I do it?
Let's take a very simple example, assuming a basic definition for Product as:
class Product
{
int code;
string name;
double price;
public:
Product(int code, const std::string& name, double price)
: code{code}, name{name}, price{price}
{}
int getCode() const { return code; }
const std::string& getName() const { return name; }
double getPrice() const { return price; }
};
You can't read in using operator>> directly into the return values from getCode(), getName() or getPrice(). Those are for accessing those values.
Instead, you need to read in the values and construct products from those values like this:
for(int x = 0; x < numProducts; ++x)
{
int code = 0;
string name;
double price = 0;
finput >> code >> name >> price;
products[i] = new Product{code,name,price};
}
Now, you could refactor this into operator>>:
std::istream& operator>>(std::istream& in, Product& p)
{
int code = 0;
string name;
double price = 0;
in >> code >> name >> price;
p = Product{code,name,price};
return in;
}
There are a bunch of other things to consider about this code:
Use std::vector<Product> instead of your own array
The examples below won't work if name has spaces
There's no error checking and operator>> can fail
In your Class, write down this function
friend ifstream& operator >> (ifstream& in, Product& p1)
{
in >> p1.code >> p1.name /* ..etc */;
return in;
}

'AMA::MyProduct': cannot instantiate abstract class

I am working on my school project that has a base class and a derived class with some other classes.
Product.h
#ifndef AMA_PRODUCT_H
#define AMA_PRODUCT_H
#include <iostream>
#include <fstream>
namespace AMA
{
const int max_sku_length = 7;
const int max_unit_length = 10;
const int max_name_length = 75;
const double TRate = 0.13;
class Product
{
private:
char m_type;
char m_sku[max_sku_length +1];
char m_unit[max_unit_length + 1];
char* m_name;
int m_Cquantity;
int m_Nquantity;
double m_price;
bool m_status;
protected:
void sku(const char* setSku) { strncpy(m_sku, setSku, max_sku_length); }
const char* name() const { return m_name; }
bool taxed() const { return m_status; }
const char* sku() const { return m_sku;}
void name(const char*);
const char* unit() const;
double price() const;
void message(const char*);
bool isClear() const;
public:
double cost() const;
bool operator==(const char* src) { return strcmp(m_sku, src) == 0; }
bool isEmpty() const { return ((m_sku[0] == '\0') && (m_name == nullptr) && (m_price == 0) && (m_Cquantity == 0)); }
int qtyNeeded() const { return m_Nquantity; }
int quantity() const { return m_Cquantity; }
int operator+=(int src) { return m_Cquantity += src; }
Product();
Product(const char* sku, const char* name, const char* unit, int qty = 0,
bool taxed = true, double price = 0.0, int qtyNeeded = 0);
Product(const Product&);
Product& operator=(const Product&);
~Product();
virtual std::fstream& store(std::fstream& file, bool addNewLine = true)const = 0;
virtual std::fstream& load(std::fstream& file) = 0;
virtual std::ostream& write(std::ostream& os, bool linear)const = 0;
virtual std::istream& read(std::istream& is) = 0;
double total_cost() const;
void quantity(int);
bool operator>(const char*) const;
bool operator>(const Product&) const;
};
std::ostream& operator<<(std::ostream&, const Product&);
std::istream& operator>>(std::istream&, Product&);
double operator+=(double&, const Product&);
}
#endif
MyProduct.h
#ifndef AMA_MY_PRODUCT_H
#define AMA_MY_PRODUCT_H
#include <fstream>
#include "Product.h"
#include "ErrorState.h"
namespace AMA {
class MyProduct : public Product {
public:
MyProduct();
MyProduct(const char* sku, const char* name, const char* unit, int qty = 0,
bool isTaxed = true, double price = 0.0, int qtyNeeded = 0);
const char* sku() const;
const char* name() const;
const char* unit() const;
bool taxed() const;
double price() const;
double cost() const;
};
class Test {
MyProduct product; // Error
const char* filename;
public:
Test(const char* file);
Test(const char* file, const char* theSku, const char* theName);
std::fstream& store(std::fstream& file, bool addNewLine = true) const;
std::fstream& load(std::fstream& file);
std::ostream& write(std::ostream& os, bool linear) const;
std::istream& read(std::istream& is);
int operator+=(int value);
bool operator==(const char* sku) const;
friend std::ostream& operator<<(std::ostream& os, const Test& test);
friend double operator+=(double& d, const Test& test);
friend std::istream& operator>>(std::istream& is, Test& test);
};
}
#endif
MyProduct.cpp
#include <iomanip>
#include <fstream>
#include <cstring>
#include "MyProduct.h"
#ifdef TAB
#undef TAB
#endif
#define TAB '\t'
using namespace std;
namespace AMA {
MyProduct::MyProduct() : Product("", "", "") {}
MyProduct::MyProduct(const char* sku, const char* name, const char* unit, int qty,
bool isTaxed, double price, int qtyNeeded) :
Product(sku, name, unit, qty, isTaxed, price, qtyNeeded) {}
const char* MyProduct::sku() const { return Product::sku(); }
const char* MyProduct::name() const { return Product::name(); }
const char* MyProduct::unit() const { return Product::unit(); }
bool MyProduct::taxed() const { return Product::taxed(); }
double MyProduct::price() const { return Product::price(); }
double MyProduct::cost() const { return Product::cost(); }
Test::Test(const char* file) : filename(file) { }
Test::Test(const char* file, const char* theSku, const char* theName) :
product(theSku, theName, ""), filename(file) { }
std::fstream& Test::store(std::fstream& file, bool addNewLine) const {
if (!product.isEmpty()) {
file.open(filename, ios::out | ios::app);
file << product.sku() << TAB << product.name() << TAB << product.unit() << TAB <<
(product.taxed() ? 1 : 0) << TAB << product.price() << TAB << product.quantity() << TAB <<
product.qtyNeeded() << endl;
file.clear();
file.close();
}
return file;
}
std::fstream& Test::load(std::fstream& file) {
char sku_[max_sku_length + 1];
char name[max_name_length + 1];
char unit[max_unit_length + 1];
int quantity, qtyNeeded;
double price_;
char taxed_;
file.open(filename, ios::in);
file >> sku_;
file >> name;
file >> unit;
file >> taxed_;
file >> price_;
file >> quantity;
file >> qtyNeeded;
file.clear();
file.close();
product = MyProduct(sku_, name, unit, quantity, taxed_ != 0, price_, qtyNeeded); //ERROR
return file;
}
std::ostream& Test::write(std::ostream& os, bool linear) const {
return product.isEmpty() ? os : (os << product.sku() << ": " << product.name() << ", quantity: "
<< product.quantity() << ", quantity needed:" << product.qtyNeeded()
<< ", Cost: " << fixed << setprecision(2) << product.cost());
}
std::istream& Test::read(std::istream& is) {
char sku_[max_sku_length + 1];
char name[max_name_length + 1];
char unit[max_unit_length + 1];
int quantity, qtyNeeded;
double price_;
char taxed_;
cout << " Sku: ";
is >> sku_;
cout << " Name (no spaces): ";
is >> name;
cout << " Unit: ";
is >> unit;
cout << " Taxed? (y/n): ";
is >> taxed_;
cout << " Price: ";
is >> price_;
cout << " Quantity On hand: ";
is >> quantity;
cout << " Quantity Needed: ";
is >> qtyNeeded;
product = MyProduct(sku_, name, unit, quantity, taxed_ != 0, price_, qtyNeeded); //ERROR
return is;
}
int Test::operator+=(int value) {
product.quantity(product += value);
return product.quantity();
}
bool Test::operator==(const char* sku) const {
return !std::strcmp(product.sku(), sku);
}
std::ostream& operator<<(std::ostream& os, const Test& test) {
return test.product.write(os, true);
}
double operator+=(double& d, const Test& test) {
return d += test.product.total_cost();
}
std::istream& operator>>(std::istream& is, Test& test) {
return test.product.read(is);
}
}
I am getting errors that I don't really know how to fix
object of abstract class type "AMA::MyProduct" is not allowed
'AMA::MyProduct': cannot instantiate abstract class
a cast to abstract class "AMA::MyProduct" is not allowed
Can someone help me out please?
The errors are self explanatory.
AMA::MyProduct is an abstract class, and such it cannot be instantiated directly.
A class is abstract when it has at least 1 abstract method (virtual and = 0 keywords on it). An abstract method MUST be overridden in a derived class, and you MUST instantiate that derived class, not the abstract class.
AMA::MyProduct is abstract because it does not override the 4 abstract methods it inherits from AMA::Product:
virtual std::fstream& store(std::fstream& file, bool addNewLine = true)const = 0;
virtual std::fstream& load(std::fstream& file) = 0;
virtual std::ostream& write(std::ostream& os, bool linear)const = 0;
virtual std::istream& read(std::istream& is) = 0;
You implemented them in AMA::Test instead of in AMA::MyProduct.

C++ ostream output wrong [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a problem and I can't solve it.
note: I can't use any string/strlen/strcmp and such functions
My problem is when I'm trying to print obj after cin, when I don't put him value it prints garbage, and if I put value it change it by cin it print it well.
#ifndef __STRING_H__
#define __STRING_H__
#include <iostream>
using namespace std;
class String {
private:
char* Str; //pointer to string
int Str_s; // size of string public:
String(char* str = NULL);
~String();
void const print() const; //check
//~~~~~~~~~~~~~~~~~~
// operators
//~~~~~~~~~~~~~~~~~
String& operator=(const String& str);
bool operator==(const String& s) const;
bool operator!=(const String& s) const;
void operator-=(const char c);
void operator+=(const char c);
char& operator[](const int index) const;
//~~~~~~~~~~~~~~~~~~
// i/o ~~ operators
//~~~~~~~~~~~~~~~~~
friend ostream& operator<<(ostream&, const String& s);
friend istream& operator>>(istream&, String& s);
//~~~~~~~~~~~~~~~~~~
// arrange method
//~~~~~~~~~~~~~~~~~
void Letters(); // arrange all letter in sentence
void Space(); //remove all unwanted spaces
void Set_Str_s(int num) {
this->Str_s = num;
}
int Get_Str_s() {
return this->Str_s;
}
//~~~~~~~~~~~~~~~~~~
// methods
//~~~~~~~~~~~~~~~~~
char const* STR() {
return Str;
}
};
#endif
ostream& operator<<(ostream& output, const String& s) {
//char *c = s.Str;
//output << c << endl;
for (int i = 0; i < s.Str_s; i++) {
cout << s.Str[i];
}
return output;
}
istream& operator>>(istream& input, String& s) {
if (s.Str == NULL) {
s.Str_s = 0;
char temp[BUFFER];
int i = 0, j = 0;
cin.getline(temp, BUFFER);
while (temp[i] != NULL) {
s.Str_s++;
i++;
}
//s.Str = new char[s.Str_s];
s.Str = temp;
} else {
input >> s.Str;
}
return input;
}
#include <iostream>
using namespace std;
#include "string_head.h"
#include "Definition_head.h"
#include "Menu_head.h"
int main() {
char* c = "hi";
char* h = "lilo";
String s, m(c);
cin >> s;
cin >> m;
cout << s;
cout << endl;
cout << m;
}
The following line is a problem:
s.Str = temp;
you are storing a pointer to a local array that will be deleted when the function returns. Use something like:
s.Str = strdup(temp);
If your platform doesn't support strdup, you can implement it. It's not too hard.
The following line is also a problem:
input >> s.Str;
If there isn't enough memory to hold the string being read, you will be writing into memory that you are not supposed to.

cannot swap objects in an array in C++

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);
}