I've been at this for hours, but I can't seem to locate where the core dump is coming from. I've limited it down to the main constructor and a couple functions but I cant find where the error is coming from. Any help would be appreciated.
destructor
Vehicle:: ~Vehicle(){
delete [] name;
}
base header
#ifndef VEHICLE_H
#define VEHICLE_H
#include <iostream>
#include <string>
using namespace std;
class Vehicle{
protected:
char *name;
static ostream *out ;
public:
Vehicle();
Vehicle(string &n);
Vehicle (const Vehicle & b);
~Vehicle();
Vehicle& operator =(const Vehicle &b);
virtual void print(void) = 0;
virtual void read(void) = 0;
};
#endif // VEHICLE_H
Constructor in base implementation
Vehicle :: Vehicle(){
name = new char[1];
strcpy(name[0], "");
}
Vehicle :: Vehicle(string &n){
int len = n.length()+ 1;
name = new char[len];
strcpy(name,n.c_str());
}
Vehicle :: Vehicle(const Vehicle & v){
int len = strlen(v.name)+ 1;
name = new char[len];
strcpy(name,v.name);
}
Header for inherited class
#ifndef MOTORVEHICLE_H
#define MOTORVEHICLE_H
#include <cstring>
#include "vehicle.h"
class MotorVehicle: public Vehicle{
protected:
string make;
string model;
double mpg;
public:
MotorVehicle();
MotorVehicle (const string &n,const string &m = "",const string &md = "", const double &mp = 0.0);
//accessor functions
string getName()const;
string getMake()const;
string getModel()const;
double getMpg()const;
ostream & getOut();
//mutator functions
string setName();
void setMake();
void setModel();
void setMpg();
void setOut(ostream & o);
//virtual functions
void print();
void read();
};
#endif // MOTORVEHICLE_H
Inherited class.
#include "motorVehicle.h"
#include <string>
#include <iostream>
MotorVehicle:: MotorVehicle(): Vehicle(), make(""), model(""), mpg(0.0){
make = "";
model = "";
mpg = 0.0;
}
MotorVehicle :: MotorVehicle(const string &n, const string &m, const string &md, const double &mp){
int len = n.length()+ 1;
delete [] name;
name = new char[len];
strcpy(name,n.c_str());
make = m;
model = md;
mpg = mp;
}
//accessor functions
string MotorVehicle :: getName()const{
string temp(name);
return temp;
}
string MotorVehicle :: getMake()const {
return make;
}
string MotorVehicle :: getModel()const {
return model;
}
double MotorVehicle :: getMpg()const {
return mpg;
}
ostream & MotorVehicle :: getOut(){
return *out;
}
//mutator functions
string MotorVehicle :: setName(){
cerr << "dododd" <<endl;
string nm1;
cin >> nm1;
int len = nm1.length()+ 1;
delete [] name;
name = new char[len];
strcpy(name,nm1.c_str());
}
void MotorVehicle :: setMake(){
cin >> make;
}
void MotorVehicle :: setModel(){
cin >> model;
}
void MotorVehicle :: setMpg(){
cin >> mpg;
}
void MotorVehicle :: setOut(ostream & o){
out = &o;
}
//virtual function
void MotorVehicle :: print(){
*out << name << make << model << mpg <<" ";
}
void MotorVehicle :: read(){
*out << "Please enter name for this Vehicle: " << endl;
setName();
*out << "Please enter make for this Vehicle: " << endl;
setMake();
*out << "Please enter model for this Vehicle: " << endl;
setModel();
*out << "Please enter miles per gallon for this Vehicle: " << endl;
setMpg();
}
Main
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include "motorVehicle.h"
// car.h & truck.h included twice to test #ifndef #define ... #endif structure
#include "car.h"
#include "car.h"
#include "truck.h"
#include "truck.h"
typedef vector<MotorVehicle *> vectorOfMotorVehicle;
using namespace std;
// prompt the user for the Vehicle type to create, and get the reply
string prompt(void);
int main() {
vectorOfMotorVehicle v; // store dynamically created MotorVehicles
// or objects derived from MotorVehicles
int numVehicles = 0; // denotes how many MotorVehicles we have
string reply; // indicates type of MotorVehicle to build
bool error = false; // set when a user response is in error
string outputLocation; // where the output of print() will go
ofstream *out = NULL;
MotorVehicle *m;
// uncomment following line to test that Vehicle is an abstract base class
// Vehicle theVehicle;
// push a Vehicle into the vector so first "real" Vehicle is at position 1
m = new MotorVehicle("None");
v.push_back(m);
// chose where the output will go
cout << "Where would you like the output? ";
cin >> outputLocation;
if (outputLocation == "stdout") {
; // no action to take, because stdout (i.e., cout) is the default
} else if (outputLocation == "stderr") {
v[0]->setOut(cerr);
} else {
out = new ofstream;
out->open(outputLocation.c_str());
if (out->fail()) {
cerr << "Error: error writing to " << outputLocation << endl;
return 1;
}
v[0]->setOut(*out);
}
// get the type of Vehicle to create
reply = prompt();
// loop, reading vehicle descriptions, until a "quit" command is received
while (reply != "quit") {
// create the new MotorVehicle object and push it into the vector
switch (toupper(reply[0])) {
case 'T' : m = (MotorVehicle *) (new Truck);
v.push_back(m);
break;
case 'C' : m = (MotorVehicle *) (new Car);
v.push_back(m);
break;
case 'Q' : reply = "quit";
continue;
default : cerr << "Incorrect response\n\n";
error = true;
}
// if no error, then we have a new Vehicle to initialize via read()
if (!error) {
numVehicles++;
v[numVehicles]->read();
}
// reset error flag, and request a new Vehicle type
error = false;
reply = prompt();
}
// report on what Vehicles were created to test read() and print()
for (int i = 0; i <= numVehicles; i++) {
//*out << "Vehicle " << i << endl;
// print the Vehicle characteristics (attributes)
v[i]->print();
//*out << endl;
// free the storage for this Vehicle
delete v[i];
}
// if we opened an output file, then close it
if (out != NULL) {
out->close();
delete out;
}
return 0;
}
// prompt the user for the Vehicle type to create, and get the reply
string prompt() {
string reply; // the user reponse to the prompt
// prompt for and get user response
cout << "\nWhich type of vehicle would you like to initialize"
<< "\n--car or truck (or \"quit\" to exit): ";
cin >> reply;
return reply;
}
I tried to narrow it down as much as possible, but the other two inherited classes follow a similar inheritance so I omitted it. Any help would be hugely appreciated. Thanks again
Related
I am trying to print my vector in the display function, but it fails. I'm about 80% sure my syntax is correct. I have tried passing it from class to class. I am sure the file is being read in correctly because when I put my for loop in ClientProcessing() it works fine but I want to separate them.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
// struct to hold the initial information of each client
struct Clients
{
string client_name = " "; // first and last as one line
char account_type = ' '; // C for Checking - S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
};
// Prototype for Account Manager
class AccManager
{
public:
vector<Clients> client_info;
string client_name = ""; // first and last as one line
char account_type = ' '; // C for Checking / S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
AccManager(){};
void set_name(string n) {client_name = n;};
string get_name(){return client_name;};
void set_type(char t){account_type = t;};
char get_type(){return account_type;};
void set_initial_deposit(double d){initial_deposit = d;};
double get_initial_deposit(){return initial_deposit;};
};
// Prototype for the UI - User interface
class UI
{
public:
void ClientProcessing();
void ShowClientInfo();
};
int main()
{
UI ui;
ui.ClientProcessing();
ui.ShowClientInfo();
}
// A module that reads in the the client data file
void UI::ClientProcessing()
{
ifstream infile;
AccManager a;
int i = 0;
cout << "Processing client information...\n";
infile.open("client_data.txt");
if(infile.is_open()){
cout << "Opened client file sucessfully! \n";
while(!infile.eof()){
while (i < 1){
getline(infile, a.client_name, '\t');
a.set_name(a.client_name);
a.client_info.push_back(Clients());
a.client_info[i].client_name = a.get_name();
i++;
}
}
}
else{
cout << "Error opening file! \n";
}
infile.close();
}
// A module to display the client info as a table
void UI::ShowClientInfo()
{
AccManager a;
cout << "Name D\n";
for(int i = 0; i < a.client_info.size(); i++){
cout << a.client_info[i].client_name; // Will not print here
}
}
Converted my code to the following and passed in the vector. It worked!
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
// struct to hold the initial information of each client
struct Clients
{
string client_name = " "; // first and last as one line
char account_type = ' '; // C for Checking - S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
};
// Prototype for Account Manager
class AccManager
{
public:
vector<Clients> client_info;
string client_name = ""; // first and last as one line
char account_type = ' '; // C for Checking / S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
AccManager(){};
void set_name(string n) {client_name = n;};
string get_name(){return client_name;};
void set_type(char t){account_type = t;};
char get_type(){return account_type;};
void set_initial_deposit(double d){initial_deposit = d;};
double get_initial_deposit(){return initial_deposit;};
};
// Prototype for the UI - User interface
class UI
{
public:
void ClientProcessing(vector<Clients> &client_info);
void ShowClientInfo(vector<Clients> client_info);
};
int main()
{
UI ui;
AccManager a;
ui.ClientProcessing(a.client_info);
ui.ShowClientInfo(a.client_info);
}
// A module that reads in the the client data file
void UI::ClientProcessing(vector<Clients> &client_info)
{ AccManager a;
ifstream infile;
int i = 0;
cout << "Processing client information...\n";
infile.open("client_data.txt");
if(infile.is_open()){
cout << "Opened client file sucessfully! \n";
while(!infile.eof()){
while (i < 1){
getline(infile, a.client_name, '\t');
a.set_name(a.client_name);
client_info.push_back(Clients());
client_info[i].client_name = a.get_name();
i++;
}
}
}
else{
cout << "Error opening file! \n";
}
infile.close();
}
// A module to display the client info as a table
void UI::ShowClientInfo(vector<Clients> client_info)
{
cout << "Name D\n";
for(int i = 0; i < client_info.size(); i++){
cout << client_info[i].client_name;
}
}
Getting an error that says
..\src\CS20 Lab 2 Part 2.cpp:75:38: error: invalid new-expression of abstract class type 'CS_Student'
Base Class:
/*
* Student.h
*
* Created on: Jan 23, 2020
* Author: Student
*/
enter code here
#ifndef STUDENT_H_`#define STUDENT_H_
#include <string>
using namespace std;
class Student {
protected:
string *name;
int *age;
public:
Student();
void setName(string s) ;
void setAge(int i);
string getName() const;
int getAge() const;
virtual void print() = 0;
virtual ~Student();
};
#endif /* STUDENT_H_ */
Student.cpp:
/*
* Student.h
*
* Created on: Jan 23, 2020
* Author: Student
*/
#ifndef STUDENT_H_
#define STUDENT_H_
#include <string>
using namespace std;
class Student {
protected:
string *name;
int *age;
public:
Student();
void setName(string s) ;
void setAge(int i);
string getName() const;
int getAge() const;
virtual void print() = 0;
virtual ~Student();
};
#endif /* STUDENT_H_ */
Derived Class:
/*
* CSStudent.cpp
*
* Created on: Jan 23, 2020
* Author: Student
*/
#include <string>
#include <iostream>
#include "CS_Student.h"
#include "Student.h"
using namespace std;
CS_Student::CS_Student() {
favProgLang = new string;
cout << "CS_Student object created!" << endl;
}
void CS_Student::setFavProgLang(string s){
*favProgLang = s;
}
string CS_Student::getFavProgLang() const{
return *favProgLang;
}
void CS_Student::print() const{
cout << "\nPRINT REPORT FOR CS_STUDENT OBJECT" << endl;
cout << "\tName: " << *name << endl;
cout << "\tAge: " << *age << endl;
cout << "\tFavorite Programming Language: " << *favProgLang << endl;
}
CS_Student::~CS_Student() {
delete favProgLang;
cout << "CS_Student object destroyed!" << endl;
}
/*
void setFavProgLang(string s);
string getFavProgLang() const;
void print() const;
*/
Derived header:
/*
* CSStudent.h
*
* Created on: Jan 23, 2020
* Author: Student
*/
#ifndef CS_STUDENT_H_
#define CS_STUDENT_H_
#include <string>
#include "Student.h"
#include <iostream>
using namespace std;
class CS_Student: public Student {
private:
string *favProgLang;
public:
CS_Student();
void setFavProgLang(string s);
string getFavProgLang() const;
void print() const;
virtual ~CS_Student();
};
#endif /* CS_STUDENT_H_ */
Main:
#include "CS_Student.h"
#include "EnglishStudent.h"
/*******************************************************************************
* Function Prototypes
*******************************************************************************/
#include <iostream>
#include <string>
using namespace std;
void getInput(CS_Student**, const int);
void getInput(EnglishStudent**, const int);
void display(Student*);
/*******************************************************************************
* int main()
* Starting point of the program.
*
* Output:
* An integer to signal to the OS the exit code.
*******************************************************************************/
int main() {
// variables
const int CS_SIZE = 2;
const int ENG_SIZE = 3;
CS_Student* csArray[CS_SIZE];
EnglishStudent* engArray[ENG_SIZE];
// call the getInput method overloads for both arrays
getInput(csArray, CS_SIZE);
getInput(engArray, ENG_SIZE);
// call the polymorphic display function for both arrays
for (int i = 0; i < CS_SIZE; i++) {
display(csArray[i]);
}
for (int i = 0; i < ENG_SIZE; i++) {
display(engArray[i]);
}
// release the dynamic memory for objects inside both arrays
for (int i = 0; i < CS_SIZE; i++) {
delete csArray[i];
}
for (int i = 0; i < ENG_SIZE; i++) {
delete engArray[i];
}
// terminate
return 0;
}
/*******************************************************************************
* void getInput(CS_Student** objArray, const int SIZE)
* Use a for loop to create dynamic CS student objects. Prompt the user for the
* name/age/favorite programming language of each CS student. Store the
* information in the dynamic object.
*
* Inputs:
* objArray - a double-pointer that should be treated as an array of dynamic
* CS student objects
* SIZE - a constant integer that represents the size of the array
*******************************************************************************/
void getInput(CS_Student** objArray, const int SIZE) {
// variables
string name = "", fpl = "";
int age = 0;
// for each CS student
for (int i = 0; i < SIZE; i++) {
// create the dynamic CS student object
objArray[i] = new CS_Student();
// prompt and store the name of the current CS student
cout << "Enter the name for CS student #" << i + 1 << ": ";
getline(cin, name);
// prompt and store for the age of the current CS student
cout << "Enter the age for CS student #" << i + 1 << ": ";
cin >> age;
// need to ignore the newline in the buffer
cin.ignore();
// prompt and store the favorite programming language of the current
// CS student
cout << "Enter the favorite programming language for CS student #"
<< i + 1 << ": ";
getline(cin, fpl);
// add the data to the dynamic object
objArray[i]->setName(name);
objArray[i]->setAge(age);
objArray[i]->setFavProgLang(fpl);
}
}
/*******************************************************************************
* void getInput(EnglishStudent** objArray, const int SIZE)
* Use a for loop to create dynamic English student objects. Prompt the user
* for the name/age/favorite book of each English student. Store the
* information in the dynamic object.
*
* Inputs:
* objArray - a double-pointer that should be treated as an array of dynamic
* English student objects
* SIZE - a constant integer that represents the size of the array
*******************************************************************************/
void getInput(EnglishStudent** objArray, const int SIZE) {
// variables
string name = "", book = "";
int age = 0;
// for each English student
for (int i = 0; i < SIZE; i++) {
// create the dynamic English student object
objArray[i] = new EnglishStudent();
// prompt and store the name of the current English student
cout << "Enter the name for English student #" << i + 1 << ": ";
getline(cin, name);
// prompt and store for the age of the current English student
cout << "Enter the age for English student #" << i + 1 << ": ";
cin >> age;
// need to ignore the newline in the buffer
cin.ignore();
// prompt and store the favorite book of the current English student
cout << "Enter the favorite book for English student #"
<< i + 1 << ": ";
getline(cin, book);
// add the data to the dynamic object
objArray[i]->setName(name);
objArray[i]->setAge(age);
objArray[i]->setFavBook(book);
}
}
/*******************************************************************************
* void display(Student* obj)
* A polymorphic function. Simply calls the (virtual) print method. Used to
* demonstrate polymorphism. Any derived class that inherits from the Student
* class can be used as an argument.
*
* Input:
* obj - a pointer to an object that inherits from the Student class
*******************************************************************************/
void display(Student* obj) {
obj->print();
}
Really confused because Student is my base class which has the pure virtual function
virtual void print() = 0;
and it's overridden in CS_Student
void CS_Student::print() const
I've also tried changing CS_Student here to Student and it doesn't change anything. Thanks in advance
Base: virtual void print() = 0;
Derived: void print() const;
That extra const in the derived version changes the signature of the derived function, the instance variable this is const, so that it doesn't match the base function. Either the base must be const or the derived must not be const. Prefer the former.
Eg.
virtual void print() = 0;
becomes
virtual void print() const= 0;
In C++ and more recent standard revisions you can catch this more easily by marking all functions you expect to override a base class function with the override keyword. This almost always results in a more easily understood error message.
Eg.
void print() const override;
results in (on my tool chain)
error: 'void CS_Student::print() const' marked 'override', but does not override
void print() const override;
I have this requirement.
I am trying to make a simple database schema, a little different than what I have seen in here. I have a class file (client.h) with it's implementation (client.cpp):
#ifndef CLIENT_H_
#define CLIENT_H_
#include <iostream>
using namespace std;
class Client {
public:
// constructors
Client();
Client(string new_name, string new_tel, string new_addr);
// getters
string getName();
string getAddr();
string getTel();
// setters
void setName(string);
void setAddr(string);
void setTel(string);
void display();
void input();
private:
// fields
string name;
string addr;
string tel;
};
#endif /* CLIENT_H_ */
/*
*ad client.cpp
*
* Created on: Jan 12, 2017
* Author: niksarid
*/
#include <iostream>
#include "client.h"
using namespace std;
Client::Client() {
setName("");
setAddr("");
setTel("");
}
Client::Client(std::string new_name, std::string new_addr, std::string new_tel) {
setName(new_name);
setAddr(new_addr);
setTel(new_tel);
}
string Client::getName() {
return name;
}
string Client::getAddr() {
return addr;
}
string Client::getTel() {
return tel;
}
void Client::setName(string p_name) {
name = p_name;
}
void Client::setAddr(string p_addr) {
addr = p_addr;
}
void Client::setTel(string p_tel) {
tel = p_tel;
}
void Client::input() {
string tmp;
cout << "INPUT CLIENT INFO" << endl;
cout << "Name: ";
cin >> tmp;
setName(tmp);
cout << "Address: ";
cin >> tmp;
setAddr(tmp);
cout << "Telephone: ";
cin >> tmp;
setTel(tmp);
}
void Client::display() {
cout << name << "\t" << addr << "\t" << tel << endl;
}
So I am trying to make a Company class that will hold a vector of Clients and at the startup of the program it will load the datafile "clients.dat", into the vector. I will be able to add a client or delete a client from the vector. At the end the vector will be saved back to "clients.dat".
So, the (company.h) file is like this:
class Company {
public:
Company();
~Company();
void add_client();
void print_clients();
void loadClientsFromFile();
void saveClientsToFile();
private:
vector<Client> clients;
} cmp;
#endif /* COMPANY_H_ */
but I can't seem to reference clients vector in any of the public methods of the class company.
EDIT: Sorry! Forgot the important part!!
For example when I try to add_client(),
void add_client() {
Client c;
c.input();
clients.push_back(c);
}
but I get
../src/company.cpp:49:2: error: 'clients' was not declared in this scope
clients.push_back(c);
So, how to achieve that?
As Morgan mentioned in the comments, this problem typically arises when you try to define the member function in your implementation file, but forget to add the class name as prefix (e.g. void add_client() {} instead of void Company::add_client() {}.
This mistake is common and can easily go unnoticed, since it is perfectly legal to define a new free function called add_client in your file, that would have nothing to do with the Company class. That's why the compiler only complains when you try to access a data member, but not before.
Here is a picture of the error:
I have created a basic class that would hold the information of a sports team. When I am attempting to compare two teams with each other with the this pointer, I am receiving an error. Here are my two files. Hopefully, it is just a simple error.
Team.cpp
#include "Team.h"
#include <string>
#include <sstream>
using namespace std;
Team::Team()
{
teamName = "The Strings";
winNum = 0;
lossNum = 0;
numPlayers = 11;
points = 0;
}
Team::Team(const char newName, int newPlayers)
{
stringstream move;
string strName;
move << newName;
move >> strName;
teamName = strName;
numPlayers = newPlayers;
}
void Team::display() // displays information about the team.
{
cout << "Team name:" << teamName << endl;
cout << "This team has " << numPlayers << " players" << endl;
cout << "This team has " << winNum << " wins and " << lossNum << endl;
}
void Team::addWins() // increment the number of wins
{
winNum = winNum + 1;
}
void Team::addLosses() // increment the number of losses.
{
lossNum = lossNum + 1;
}
void Team::addPlayer(int nrPlayers)
{
numPlayers = numPlayers + nrPlayers;
}
void Team::delPlayers(int nrPlayers)
{
numPlayers = numPlayers - nrPlayers;
}
void Team::setTeam(char name[], int players, int wins, int losses)
{
string strname(name);
teamName = name;
numPlayers = players;
winNum = wins;
lossNum = losses;
}
bool isBetter(const Team &other)
{
if (this->points > other.points)
{
return true;
}
else
{
return false;
}
}
int Team::getWins() // returns the number of wins for a team object
{
return winNum;
}
int Team::getLosses() // returns the number of losses for a team object
{
return lossNum;
}
int Team::getPoints() // returns the number of points a team has
{
points = winNum - lossNum;
return points;
}
Team.h
#ifndef TEAM_H
#define TEAM_H
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
// definition of class Dice
class Team
{
private:
int numPlayers,
winNum,
lossNum;
int points;
string teamName ;
public:
// default constructor: initializes the face of a new
// Dice object to 1
Team();
Team(const char newName, int newPlayers);
void display(); // displays information about the team.
void addWins(); // increment the number of wins
void addLosses(); // increment the number of losses.
void addPlayer(int nrPlayers);
void delPlayers(int nrPlayers);
void setTeam(char name[], int players, int wins, int losses);
bool isBetter(const Team &other);
int getWins(); // returns the number of wins for a team object
int getLosses(); // returns the number of losses for a team object
int getPoints(); // returns the number of points a team has
};
#endif
My task is as follows :
Using pointers to class fields, create menu allowing selection of ice, that Person can buy in Ice shop. Buyer will be charged with waffel and ice costs.
Selection of ice and charging buyers account must be shown in program.
Here's my Person class :
#include <iostream>
using namespace std;
class Iceshop {
const double waffel_price = 1;
public:
}
class Person {
static int NUMBER;
char* name;
int age;
const int number;
double plus, minus;
public:
class Account {
int number;
double resources;
public:
Account(int number, double resources)
: number(number), resources(resources)
{}
}
Person(const char* n, int age)
: name(strcpy(new char[strlen(n)+1],n)),
number(++NUMBER), plus(0), minus(0), age(age)
{}
Person::~Person(){
cout << "Destroying resources" << endl;
delete [] name;
}
friend void show(Person &p);
int* take_age(){
return &age;
}
char* take_name(){
return name;
}
void init(char* n, int a) {
name = n;
age = a;
}
Person& remittance(double d) { plus += d; return *this; }
Person& paycheck(double d) { minus += d; return *this; }
Account* getAccount();
};
int Person::
Person::Account* Person::getAccount() {
return new Account(number, plus - minus);
}
void Person::Account::remittance(double d){
resources = resources + d;
}
void Person::Account::paycheck(double d){
resources = resources - d;
}
void show(Person *p){
cout << "Name: " << p->take_name() << "," << "age: " << p->take_age() << endl;
}
int main(void) {
Person *p = new Person;
p->init("Mary", 25);
show(p);
p->remittance(100);
system("PAUSE");
return 0;
}
How to change this into using pointers to fields ?
class Iceshop {
const double waffel_price;
int menu_options;
double[] menu_prices;
char* menu_names;
char* name;
public:
IceShop(char*c)
: name(strcpy(new char[strlen(n)+1],n)),
waffel_price(1), menu(0)
{}
void init(int[] n){
menu_options = n;
}
void showMenu(Iceshop &i){
int list;
list = &i
char* sorts = i->menu_names;
int count=0;
while(count < list){
cout << count+1 << ")" << sorts[count] << endl;
++count;
}
}
void createMenu(Iceshop *i){
for(int j=0; j <(i->menu_options), ++j){
cout << "Ice name: ";
cin >> i->menu_names[j];
endl;
cout << "Ice cost: "
cin >> i->menu_prices[j];
endl;
}
}
void chargeClient(Person *p, Iceshop* i, int sel){
p->remittance( (i->menu_prices[sel])+(i->waffel_price) );
}
};
You could try to build a menu driven UI.
Something like this (copy paste from a forum, for more examples search for 'C++ console' menu' or something like it on google.
int choice = 0;
while (choice != 4)
{
cout <<"Enter choice:"<< endl <<
"1) ice 1" << endl <<
"2) ice 2" << endl<<
"3) ice 3" << endl <<
"4) exit" << endl;
cin >> choice;
switch(choice)
{
case 1:
//show menu to buy or cancel
break;
case 2:
//show menu to buy or cancel
break;
}
//etc
}
Here is what I would do. Note that it's not exactly what you're looking for and, well, abstract situation modelling is always tough :)
But I hope this code would make you understand what you have to do.
Also, I am not exactly sure about using pointers to class fields, because this tends to be a situation where pointer usage is superflous.
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
// Some abstract type used to measure prices
typedef size_t money_t;
struct Item {
// Item's name and price
std::string name;
money_t price;
// Could also have something that makes
// it an item, but this is not necessary
// This could be anything, because we're actually
// modelling an abstract situation
// (...)
// Note that we don't allow unnamed items
Item(const std::string& name, const money_t& price = 0) : name(name), price(price) { }
// Note here that items are treated as 'same' only by names
// This means we're actually talking about 'logical groups' of items
bool operator==(const Item& item) const { return name == item.name; }
bool operator==(const std::string& item_name) const { return name == item_name; }
};
class Store {
private:
// Store's item storage
// Note that items actually represent infinite groups
// of items (in our case store is an abstract store
// which items simply can't end)
std::vector<Item> items;
public:
// Initialize a store that doesn't sell anything
Store() { }
// Initialize a store that could sell specified types of items
Store(const std::vector<Item>& items) : items(items) { }
// Show what we actually sell in this store
void EnumerateItems() const {
for (size_t i = 0; i < items.size(); ++i)
std::cout << items[i].name << " : " << items[i].price << "\n";
}
Item Sell(const std::string& name) const {
// Find appropriate item in the item list
std::vector<Item>::const_iterator what = std::find(items.begin(), items.end(), name);
// If nothing found, throw an exception
if (what == items.end()) {
throw std::domain_error("Store doesn't sell this type of item");
}
// Return item as a sold one
return (*what);
}
};
class Person {
private:
// Person's name (identity)
std::string name;
// Item's that are currently possesed
// by this person
std::vector<Item> owned_items;
// Amount of cash that this person has
money_t cash;
public:
// Note that we don't allow unnamed persons
Person(const std::string& name, const money_t& cash = 0) : name(name), cash(cash) { }
void Buy(const Item& what) {
owned_items.push_back(what);
cash -= what.price;
}
};
void GoShopping(Person& person, const Store& store) {
// Let's simulate buying one item
// You could easily make a loop and determine what to buy in
// every loop iteration
store.EnumerateItems();
person.Buy(store.Sell("Shoes"));
}
int main() {
// Initialize our store that sells only shoes
std::vector<Item> items;
items.push_back(Item("Shoes", 25));
Store grocery(items);
// Initialize our person
Person jim_carrey("Jim Carrey", 500);
// The yummy part
GoShopping(jim_carrey, grocery);
return 0;
}