#include<iostream>
#include<string>
using namespace std;
class Item{
private:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
public:
void print(){
cout << "ULD: " << type << endl;
cout << "Abbreviation: " << abbrv << endl;
cout << "ULD-ID: " << uID << endl;
cout << "Aircraft: " << aircraft << endl;
cout << "Weight: " << weight << " Kilograms" << endl;
cout << "Destination: " << destination << endl;
}
friend void kilotopound(Item);
};
void kilotopound(Item I){
cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}
int main(){
Item I;
I.type = "Container";
I.uID = "AYK68943IB";
I.abbrv = "AYK";
I.aircraft = 737;
I.weight = 1654;
I.destination = "PDX";
I.print();
kilotopound(I);
return 0;
}
Starting on line 31 I'm getting the error 'std::__cxxll::string Item::type' is private within this context
I'm basically trying to make the data private from this code
class Item{
public:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
void print(){
cout << "ULD: " << type << endl;
cout << "Abbreviation: " << abbrv << endl;
cout << "ULD-ID: " << uID << endl;
cout << "Aircraft: " << aircraft << endl;
cout << "Weight: " << weight << " Kilograms" << endl;
cout << "Destination: " << destination << endl;
}
friend void kilotopound(Item);
};
void kilotopound(Item I){
cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}
int main(){
Item I;
I.type = "Container";
I.uID = "AYK68943IB";
I.abbrv = "AYK";
I.aircraft = 737;
I.weight = 1654;
I.destination = "PDX";
I.print();
kilotopound(I);
return 0;
}
Any help would be greatly appreciated, I'm just sort of lost on how I can resolve the error. Thanks!
Also I need to be able to copy and output the copied data once again if anyone can help with that as well, with private data too. Thanks again!
#include<iostream>
#include<string>
using namespace std;
class Item{
private:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
public:
Item(string t, string a, string u, int aC, double w, string d){
type = t;
abbrv = a;
uID = u;
aircraft = aC;
weight = w;
destination = d;
}
void print() {
cout << "ULD: " << type << endl;
cout << "Abbreviation: " << abbrv << endl;
cout << "ULD-ID: " << uID << endl;
cout << "Aircraft: " << aircraft << endl;
cout << "Weight: " << weight << " Kilograms" << endl;
cout << "Destination: " << destination << endl;
}
friend void kilotopound(Item);
};
void kilotopound(Item I){
cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}
int main(){
Item I ("Container", "AYK68943IB", "AYK", 737, 1654, "PDX");
I.print();
kilotopound(I);
return 0;
}
Related
I've recently started learning c++ and for the life of me, I can't seem to get the syntax of using ostream in a class and what arguments should I pass. Here's the code:
This is the class in question:
#include <iostream>
#include <string>
using namespace std;
class Pokemon{
friend ostream& operator<<(ostream&, Pokemon);
public:
string name, level, cp;
Pokemon(string x="Pikachu", string y="5", string z="1000"){
name = x;
level = y;
cp = z;
}
Pokemon name(){
return this->name;
}
Pokemon level(){
return this->level;
}
Pokemon cp(){
return this->cp;
}
Pokemon display_stats(){
cout << this-> name << "stats are:" << endl;
cout << " " << "Attack: 2716.05" << endl;
cout << " " << "Defence: 1629.63" << endl;
cout << " " << "HP: 1086.42" << endl;
}
};
template<typename TYPE> //i dont understand this and the things i've written down here are only based on samples i've seen
ostream& operator<<(ostream& os, Pokemon & c){
os << "The level of " << c.name << " is" << c.level << " with cp of " << c.cp;
}
As you could see, I already tried constructing the ostream thing but I don't really understand how it works. This is my main function:
int main()
{
Pokemon a, b, c, d;
a = Pokemon();
b = Pokemon("Weezing");
c = Pokemon("Nidoking", 100);
d = Pokemon("Mewtwo", 50, 5432.1);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "Jessie: You are no match to me! Go " << b.name << "!" << endl;
cout << "Gary: Go lvl " << c.level << " " << c.name << "! Crush them" << endl;
cout << "Ash: " << a.name << " can do it even thouh he is only level " << a.level << endl;
cout << "Jessie: Hahaha! My " << b.name << " CP is " << b.cp << endl;
cout << "Gary: "<< c.name << " CP is " << c.cp << endl;
cout << "Ash: " << a.name << " CP is " << a.cp << endl;
cout << "Giovanni: Behold " << d.name << " is here." << endl;
d.display_stats();
return 0;
}
I'm getting errors of:
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [9], int) //on line c = Pokemon("Nidoking", 100);
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [7], int, double) //on line d = Pokemon("Mewtwo", 50, 5432.1);
All of your Pokemon class methods are returning the wrong type. And your main() is not calling any of the methods correctly at all.
Change your Pokemon class to look more like this:
#include <iostream>
#include <string>
using namespace std;
class Pokemon {
private:
string m_name;
int m_level;
double m_cp;
friend ostream& operator<<(ostream&, const Pokemon&);
public:
Pokemon(string x="Pikachu", int y=5, double z=1000) {
m_name = x;
m_level = y;
m_cp = z;
}
string name() const {
return m_name;
}
int level() const {
return m_level;
}
double cp() const {
return m_cp;
}
void display_stats() const {
cout << m_name << " stats are:" << endl;
cout << " " << "Attack: 2716.05" << endl;
cout << " " << "Defense: 1629.63" << endl;
cout << " " << "HP: 1086.42" << endl;
}
};
ostream& operator<<(ostream& os, const Pokemon &c) {
os << "The level of " << c.m_name << " is " << c.m_level << " with cp of " << c.m_cp;
return os;
}
And then change main() to look more like this:
int main()
{
Pokemon a;
Pokemon b("Weezing");
Pokemon c("Nidoking", 100);
Pokemon d("Mewtwo", 50, 5432.1);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "Jessie: You are no match to me! Go " << b.name() << "!" << endl;
cout << "Gary: Go lvl " << c.level() << " " << c.name() << "! Crush them" << endl;
cout << "Ash: " << a.name() << " can do it even though he is only level " << a.level() << endl;
cout << "Jessie: Hahaha! My " << b.name() << " CP is " << b.cp() << endl;
cout << "Gary: " << c.name() << " CP is " << c.cp() << endl;
cout << "Ash: " << a.name() << " CP is " << a.cp() << endl;
cout << "Giovanni: Behold " << d.name() << " is here." << endl;
d.display_stats();
return 0;
}
Live Demo
I'm working on an assignment in my first semester of C++ and I just can't figure out working syntax for it. I need to pass a struct as a parameter to a class function using a pointer. This code I've copied is my best attempt, and it will compile but it crashes when it asks for the first name. When I try variations in the syntax, I get errors about incomplete struct, undefined variables (warrior was or invalid operators. What am I doing wrong?
#include <iostream>
using namespace std;
class StarWars
{
public:
int totalNumber;
struct data_clone
{
int ID, timeCounter;
string name;
};
data_clone *warrior;
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
}
void input(struct data_clone *pointer, int total)
{
for(int i = 1; i <= total; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> pointer[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> pointer[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> pointer[i].timeCounter;
}
}
void lifeSpan(struct data_clone *pointer, int total)
{
for(int i = 1; i <= total; i++)
{
cout << "Warrior number " << pointer[i].name << ": " << endl;
while(pointer[i].timeCounter > 0)
{
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is alive." << endl;
pointer[i].timeCounter--;
}
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
};
int main(void)
{
StarWars clones;
clones.createClone();
clones.input(clones.warrior, clones.totalNumber);
clones.lifeSpan(clones.warrior, clones.totalNumber);
}
You don't initialise the memory warrior points to, so you're working with uninitiailised memory - always a bad thing. There's two things to keep in mind here:
When working with pointers, always initialise the memory behind them first. Prefer using RAII concepts like std::unique_ptr / std::shared_ptr
void DoStuff(Widget* w);
std::unique_ptr<Widget> pw = std::make_unique<Widget>();
DoStuff(w.get());
When working with normal variables, use the dereference / reference operators to take a pointer to the variable.
void DoStuff(Widget* w);
Widget widget;
DoStuff(&w);
struct data_clone
{
int ID, timeCounter;
string name;
};
class StarWars
{
private:
data_clone *warrior;
int totalNumber;
public:
StarWars()
{
}
~StarWars()
{
delete[] warrior; // clean up
}
void createClone();
void input();
void lifeSpan();
};
void StarWars::createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
// construct structure baased on input
warrior = new data_clone[totalNumber];
}
void StarWars::input()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "For warrior number " << i+1 << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> warrior[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> warrior[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> warrior[i].timeCounter;
}
}
void StarWars::lifeSpan()
{
std::cout<<"**********Print data**********\n";
for(int i = 0; i < totalNumber; i++)
{
cout << "Warrior number " << warrior[i].name << ": " << endl;
while(warrior[i].timeCounter > 0)
{
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is alive." << endl;
warrior[i].timeCounter--;
}
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
StarWars clones;
clones.createClone();
clones.input();
clones.lifeSpan();
return 0;
}
You never created your clones, you only read how many there should be.
Allocate space for them:
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
warrior = new data_clone[totalNumber];
}
Your array indexes are also off - an array of size N is indexed from 0 to N - 1.
But the more common way of handling this is to pass the amount to the constructor and let the object handle its own members:
class StarWars
{
public:
StarWars(int clones)
: totalNumber(clones),
warrior(new data_clone[clones])
{
}
void input()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> warrior[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> warrior[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> warrior[i].timeCounter;
}
}
void lifeSpan()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "Warrior number " << i << ": " << endl;
while(warrior[i].timeCounter > 0)
{
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is alive." << endl;
warrior[i].timeCounter--;
}
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
private:
int totalNumber;
struct data_clone
{
int ID, timeCounter;
string name;
};
data_clone *warrior;
};
int main()
{
int number = 0;
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> number;
StarWars clones(number);
clones.input();
clones.lifeSpan();
}
Note that you need to handle the destructor, the copy constructor, and the assignment operator properly as well (left as an exercise).
class StarWars
{
private:
struct data_clone
{
int ID, timeCounter;
string name;
};
public:
StarWars()
{
warrior = new data_clone[4];
}
~StarWars()
{
delete[] warrior;
}
int totalNumber;
data_clone *warrior;
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
}
void input(struct data_clone *pointer, int total)
{
for(int i = 0; i < total; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> pointer[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> pointer[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> pointer[i].timeCounter;
}
}
void lifeSpan(struct data_clone *pointer, int total)
{
for(int i = 0; i < total; i++)
{
cout << "Warrior number " << pointer[i].name << ": " << endl;
while(pointer[i].timeCounter > 0)
{
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is alive." << endl;
pointer[i].timeCounter--;
}
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
};
Note: I just hardcoded it which is not the correct way, it force you to enter only 4 tyeps of dataclone
"warrior = new data_clone[4];"
you will at least get your result
I new a memory for my child class type stock which is inherited from base class instrument, when I try to access the second element of my array, it throws error. Things are fine when I my new array size is 1
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Instrument{
public:
virtual void display(){}
virtual void output(){}
virtual void readFile(){}
virtual ~Instrument(){}
};
class Stock :
public Instrument{
public:
Stock(){
}
virtual void input(){
cout << "This is stock, please input its information: ";
cin >> name >> bidPrice >> askPrice >> lastPrice >> issueExchange;
}
virtual void display(){
cout <<"This is to display stock: "<< name << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< issueExchange << " "
<< endl;
}
virtual void output(){
ofstream myfile;
myfile.open("Stock.txt", ios::out | ios::app);
if (myfile.is_open()){
myfile << "This is a stock: "
<< name << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< issueExchange << " "
<< endl;
}
else cout << "Unable to open file";
}
virtual void readFile(){
string line;
ifstream myfile("Stock.txt");
cout << "\nThis is file stored\n";
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
}
virtual ~Stock(){}
private:
char name[13];
double bidPrice;
double askPrice;
double lastPrice;
int issueExchange;
};
int main(){
const int N = 5;//it works fine if I use N=1;
Instrument *pBase = NULL;
pBase = new Stock[N];
for (int i = 0; i < N; i++){
pBase[i].input();// here throws an exception and ends the program
pBase[i].display();
pBase[i].output();
}
pBase[N - 1].readFile();
delete[] pBase;
system("pause");
return 0;
}
Polymorphism and pointer arithmetic do not mix, because the arrangement of objects within an array depends on the most-derived size, and polymorphism loses that information. The dynamic allocation is a red herring, you can see the same problem with:
Derived array[2];
Base* p = array;
printf("%p\n", &array[0]);
printf("%p\n", p);
printf("%p\n", &array[1]);
printf("%p\n", p + 1);
printf("%z\n", sizeof (array[0]));
printf("%z\n", sizeof (*p));
Note that the pointer values using array are moving forward by sizeof (Derived), but pointer arithmetic using p is moving forward by sizeof (Base) and not finding the real objects.
Generally you would fix this using an array of Base*, instead of a single Base* combined with pointer arithmetic.
Base* pp[2];
for( auto& elem : array ) pp[&elem - array] = &elem;
printf("%p\n", &array[1]);
printf("%p\n", pp[1]);
// use (*pp[1]) or pp[1]->whatever
Another option is to use an object that remembers the original type:
Derived* allocated = new Derived[N];
std::function<Base& (int)> poly = [allocated](int i){ return allocated[i]; };
and use poly(i) instead of p[i]
But warning, you CANNOT do delete [] &poly(0); because delete[] is not polymorphic either.
Using std::unique_ptr<Derived[]> and std::bind, one could arrange for automatic deallocation when the accessor object finally goes out of scope.
Although Mr.Ben's method is absolutely right, but I totally feel that his C++ and my C++ are not the same language, his is mixing some strange things here, thus according to his idea, I tried to modify my code like this.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class Instrument{
public:
virtual void display() = 0;
virtual void output() = 0;
virtual void readFile() = 0;
virtual ~Instrument(){};
};
class Stock :
public Instrument{
public:
Stock(){
cout << "This is stock, please input its information: ";
cin >> name >> bidPrice >> askPrice >> lastPrice >> issueExchange;
}
virtual void display(){
cout << "This is to display stock: " << name << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< issueExchange << " "
<< endl;
}
virtual void output(){
ofstream myfile;
myfile.open("Stock.txt", ios::out | ios::app);
if (myfile.is_open()){
myfile << "This is a stock: "
<< name << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< issueExchange << " "
<< endl;
}
else cout << "Unable to open file";
}
virtual void readFile(){
string line;
ifstream myfile("Stock.txt");
cout << "\nThis is file stored\n";
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
}
virtual ~Stock(){}
private:
string name;
double bidPrice;
double askPrice;
double lastPrice;
int issueExchange;
};
class Option :
public Instrument{
public:
Option(){
cout << "This is option, please input its information: ";
cin >> name >> uname >> bidPrice >> askPrice >> lastPrice >> contractSize >> exp;
}
virtual void display(){
cout << "This is to display option: "
<< name << " "
<< uname << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< contractSize << " "
<< exp << " "
<< endl;
}
virtual void output(){
ofstream myfile;
myfile.open("Option.txt", ios::out | ios::app);
if (myfile.is_open()){
myfile << "This is an option: "
<< name << " "
<< uname << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< contractSize << " "
<< exp << " "
<< endl;
}
else cout << "Unable to open file";
}
virtual void readFile(){
string line;
ifstream myfile("Option.txt");
cout << "\nThis is file stored\n";
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
}
virtual ~Option(){}
private:
string name;
string uname;
double bidPrice;
double askPrice;
double lastPrice;
int contractSize;
double exp;
};
class Future :
public Instrument{
public:
Future(){
cout << "This is option, please input its information: ";
cin >> name >> uname >> bidPrice >> askPrice >> lastPrice >> contractSize >> tickSize >> contractMonth;
}
virtual void display(){
cout << "This is to display option: "
<< name << " "
<< uname << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< contractSize << " "
<< tickSize << " "
<< contractMonth << " "
<< endl;
}
virtual void output(){
ofstream myfile;
myfile.open("Future.txt", ios::out | ios::app);
if (myfile.is_open()){
myfile << "This is a future: "
<< name << " "
<< uname << " "
<< bidPrice << " "
<< askPrice << " "
<< lastPrice << " "
<< contractSize << " "
<< tickSize << " "
<< contractMonth << " "
<< endl;
}
else cout << "Unable to open file";
}
virtual void readFile(){
string line;
ifstream myfile("Future.txt");
cout << "\nThis is file stored\n";
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
}
virtual ~Future(){}
private:
string name;
string uname;
double bidPrice;
double askPrice;
double lastPrice;
int contractSize;
int tickSize;
int contractMonth;
};
int main(){
int N = 20;
//shared_ptr<Instrument> pBase[N];
vector<shared_ptr<Instrument>> pBase(N);
int i = 5;
for (i = 0; i < N; i++) pBase[i] = make_shared<Stock>();
for (i = 0; i < N; i++){
pBase[i]->display();
pBase[i]->output();
}
pBase[N - 1]->readFile();
for (i = 0; i < N; i++) pBase[i] = make_shared<Option>();
for (i = 0; i < N; i++){
pBase[i]->display();
pBase[i]->output();
}
pBase[N - 1]->readFile();
for (i = 0; i < N; i++) pBase[i] = make_shared<Future>();
for (i = 0; i < N; i++){
pBase[i]->display();
pBase[i]->output();
}
pBase[N - 1]->readFile();
system("pause");
return 0;
}
tl;dr answer: don't convert subclass array (Stock[N]) to a base class pointer (pBase). Either directly use Stock*, or create an array of pointers instead:
auto arr = new Stock*[N];
for (int i = 0; i < N; i++) {
arr[i] = new Stock();
}
// unrelated but suggested: C++11 unique_ptr is recommended:
vector<unique_ptr<Stock>> v(N);
Detailed reasons:
1) Array bracket operator is a syntactic sugar: a[b] -> *(a + b);
2) Pointer arithmetic is not polymorphic, it's always based on static types:
pBase[i] -> *(pBase+i) -> *(pBase*)((char*)pBase + sizeof(Instrument) * i);
3) This is, however, what you want:
pBase[i] -> *(pBase+i) -> *(pBase*)((char*)pBase + sizeof(Stock) * i);
4) As long as sizeof(Instrument) != sizeof(Stock), you are in trouble.
I need this program to create a new HotDogStand object that is able to track how many hot dogs are sold by each stand individually and all together, and I cannot figure out how to make my static method work to find the total number of hot dogs sold between all stands. Can someone point me in the right direction please?
#include <iostream>
using namespace std;
class HotDogStand
{
public:
HotDogStand(int id, int hds);
void justSold();
int getNumSold();
int getID();
int getTotalSold();
private:
int idNum;
int hotDogsSold;
static int totalSold;
};
HotDogStand::HotDogStand(int id, int hds)
{
idNum = id;
hotDogsSold = hds;
return;
}
void HotDogStand::justSold()
{
hotDogsSold++;
return;
}
int HotDogStand::getNumSold()
{
return hotDogsSold;
}
int HotDogStand::getID()
{
return idNum;
}
int HotDogStand::getTotalSold()
{
totalSold = 0;
totalSold += hotDogsSold;
}
int main()
{
HotDogStand s1(1, 0), s2(2, 0), s3(3, 0);
s1.justSold();
s2.justSold();
s1.justSold();
cout << "Stand " << s1.getID() << " sold " << s1.getNumSold() << "." << endl;
cout << "Stand " << s2.getID() << " sold " << s2.getNumSold() << "." << endl;
cout << "Stand " << s3.getID() << " sold " << s3.getNumSold() << "." << endl;
cout << "Total sold = " << s1.getTotalSold() << endl;
cout << endl;
s3.justSold();
s1.justSold();
cout << "Stand " << s1.getID() << " sold " << s1.getNumSold() << "." << endl;
cout << "Stand " << s2.getID() << " sold " << s2.getNumSold() << "." << endl;
cout << "Stand " << s3.getID() << " sold " << s3.getNumSold() << "." << endl;
cout << "Total sold = " << s1.getTotalSold() << endl;
}
Globally (outside of the class), you have to define the static variable:
int HotDogStand::totalSold = 0;
Change
void HotDogStand::justSold()
{
hotDogsSold++;
totalSold++; // increment here
return;
}
And
int HotDogStand::getTotalSold()
{
return totalSold; // just return value
}
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;
//create HotelRoom class
class HotelRoom
{
private:
char* ptr_guest;
char room_number[3];
int room_capacity;
int occupancy_status;
double daily_rate;
public:
HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus);
~HotelRoom();
void Display_Number();
void Display_Guest();
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
};
HotelRoom::HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus)
{
strcpy(room_number, roomNumber);
room_capacity = roomCapacity;
daily_rate = roomRate;
ptr_guest = new char[strlen(ptr_name) + 1];
strcpy(ptr_guest, ptr_name);
occupancy_status = occupancyStatus;
}
HotelRoom::~HotelRoom()
{
cout << endl;
cout << "Destructor Executed";
cout << endl;
delete [] ptr_guest;
}
void HotelRoom::Display_Guest()
{
char* temp = ptr_guest;
while(*temp != '\0')
cout << *temp++;
}
void HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Get_Capacity()
{
return room_capacity;
}
int HotelRoom::Get_Status()
{
return occupancy_status;
}
double HotelRoom::Get_Rate()
{
return daily_rate;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
double HotelRoom::Change_Rate(double newRate)
{
daily_rate = newRate;
return daily_rate;
}
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
//Declare variables to hold data
char roomNumber[3] = {'1','3','\0'};
char guestName[20];
double roomRate = 89.00;
int roomCapacity = 4;
int occupancyStatus = 0;
int status;
int checkOut;
int newCustomer;
//Ask for user input
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
HotelRoom HotelRoom1(roomNumber, roomCapacity, roomRate, guestName, status);
//Display Rooom information
cout << endl;
cout << endl;
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << "Guest's Name: ";
HotelRoom1.Display_Guest();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
//chech this guest out?
cout << "Check this guest out? ('1 = yes' '0' = no) ";
cin >> checkOut;
switch(checkOut)
{
case 1:
HotelRoom1.Change_Status(0);
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
cout << "You have checked out of room number " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity();
cout << endl;
cout << endl;
cout << "There are currently " << HotelRoom1.Get_Status() << " occupants";
cout << endl;
cout << endl;
cout << "The rate of this room was " << HotelRoom1.Get_Rate();
break;
}
//check in new guest?
cout << endl;
cout << endl;
cout << "Check in new guest? ('1 = yes' '0' = no) ";
cin >> newCustomer;
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
switch (newCustomer)
{
case 1:
HotelRoom HotelRoom2(roomNumber, roomCapacity, roomRate, guestName, status);
HotelRoom1.Change_Rate(175.00); //Change rate of room
cout << endl;
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
cout << endl;
cout << endl;
//Display new guest information
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
break;
}
cout << endl;
system("PAUSE");
return 0;
}
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
char HotelRoom::Display_Guest()
{
cout << ptr_guest;
}
string HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
These functions claim to be returning values. The first two are not, the last is not under certain conditons. Calling the first two is undefined behavior. Calling Change_Status with roomStatus > room_capacity is also undefined behavior.
There may be other problems with the code, but the elephant in the room is the undefined behavior. Any other debugging while you have undefined behavior is theoretically a waste of time.