C++ Using array and for loop to output from multiple classes - c++

I am asked to do this code and i need to use array or something similar to print out different classes. The only way i know is individually doing every single class is there a faster way of doing this. Following is the way i am using at the moment.
Ground_Transport Gobj;
Air_Transport Aobj;
Sea_Transport Sobj;
Car Cobj;
Train Tobj;
Bus Bobj;
Gobj.estimate_time();
Gobj.estimate_cost();
cout << Gobj.getName() << endl;
Bobj.estimate_time();
Bobj.estimate_cost();
cout << Bobj.getName() << endl;
Sobj.estimate_time();
Sobj.estimate_cost();
cout<<Sobj.getName()<<endl;
Aobj.estimate_time();
Aobj.estimate_cost();
cout << Aobj.getName() << endl;
Cobj.estimate_time();
Cobj.estimate_cost();
cout << Cobj.getName() << endl;
Tobj.estimate_time();
Tobj.estimate_cost();
cout << Tobj.getName() << endl;
Transport_KL_Penang Kobj;
cout << Kobj.getName() << endl;
This is the header file Transport_KL_Penang
#include <iostream>
#include <string>
using namespace std;
class Transport_KL_Penang
{
public:
Transport_KL_Penang() {}
virtual string getName() {
return Name;
}
int Time_in_hours1 ;
int Time_in_hours2 ;
int Cost_in_RM1 ;
int Cost_in_RM2 ;
void estimate_time() ;
void estimate_cost() ;
private:
static string Name;
};
void Transport_KL_Penang::estimate_time()
{
cout << "It takes " << Time_in_hours1 << "-" << Time_in_hours2 <<
" hours if you use " << Name << endl;
}
void Transport_KL_Penang::estimate_cost()
{
cout << "It will cost around " << Cost_in_RM1 << "-" << Cost_in_RM2 <<
"RM if you use " << Name << endl;
}

If you don't need a specific object name, you can write something as a code below, creating a multiples generics objects:
#include <iostream>
#include <cstdlib>
#include <time.h>
class Myclass {
private:
int randTime;
float cost;
public:
void estimate_time(){
randTime = rand()%100;
}
void estimate_cost(){
cost = randTime * 0.2;
}
float getEstimateCost(){
return cost;
}
};
int main(){
srand(time(NULL));
int numberOfObjects = 7;
Myclass obj[numberOfObjects];
//input
for(int i = 0; i < numberOfObjects; i++){
obj[i].estimate_time();
obj[i].estimate_cost();
}
// printing
for(int i = 0; i < numberOfObjects; i++){
std::cout << obj[i].getEstimateCost() << std::endl;
}
return 0;
}

Related

Clarification about function calls in cout needed

i'm doing an online c++ learning course with quiz. The last output line of this snippet is to be determined (comments added by me). Correct answer: 10. My question: why 10 and not 11?
Calling a(b) swaps the two variables, so why is the last a.a.b 0 and not 1? / Why does the a.b() in cout not affect the a.a.b?
#include <iostream>
using namespace std;
class classA {
public:
classA() { st.f = st.p = 1; }
struct { int f, p; } st;
int bfunc(void);
};
int classA::bfunc(void) { int x = st.f; st.f = st.p; st.p = x; return x; };
int main()
{
classA a;
a.st.f = 0;
cout << a.st.f << a.st.p << endl; //01
a.bfunc();
cout << a.st.f << a.st.p << endl; //10
a.bfunc();
cout << a.st.f << a.st.p << endl; //01
a.bfunc();
cout << a.st.f << a.st.p << endl; //10
cout << a.bfunc() << a.st.p << endl; //10
return 0;
}

Sorting a Class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So, I am learning about classes in C++, I created two classes, one for a University that contains a list of class Students, i managed to create students, and introduce some values to the classes, but now i want to sort the class students by student number, i tryed using the sort function, but im not succeeding. I will leave my code bellow, please give some good tips and advises, so I can improve my code. thanks
main.css
#include <iostream>
#include "university.h"
#include "students.h"
using namespace std;
int main() {
university univ = university();
return 0;
}
university.h
#pragma once
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include "students.h"
using namespace std;
class university
{
private:
list<students> lstudents;
list<students>::iterator itstudents;
public:
university();
void setStudents(list<students> lstudents);
void registerStudent();
void list();
void average();
//void sortstudents();
};
university.cpp
#include "university.h"
using namespace std;
university::university() { //constructor
string resp = "s";
int op;
bool out = true;
cout << "Enter Students:" << endl;
while (resp != "n")
{
this->registerStudent();
cout << "Continue inserting? (s/n)" << endl;
cin >> out;
cin.ignore();
}
while (out)
{
cout << "What you Want to do? (1- List Students 2- Sudent Average 3- Sort Students by Number 4- Leave)" << endl;
cin >> op;
switch (op)
{
case 1:
this->list();
break;
case 2:
this->average();
break;
/*case 3:
this->sortStudents();
break;*/
case 4:
out = false;
break;
};
}
}
void university::setStudents(list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
cout << left << setw(11) << "Number"
<< left << setw(30) << "Name"
<< left << setw(30) << "Course"
<< left << setw(10) << "Average";
cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//cout << "Total de pacientes:" << somatorio << endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
cout << "Average:" << average / sum << endl;
}
//void university::sortstudents() {
// sort(lstudents.begin(), lstudents.end(), &students::compare);
//}
students.h
as you can see the commented code is my attempts on sorting the class student my number
#pragma once
#include <iomanip>
#include <algorithm>
#include <list>
#include "university.h"
using namespace std;
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
//friend bool operator<(estudantes& left,estudantes& right) { return left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
//bool compare(estudantes a, estudantes b);
};
students.cpp
#include "students.h"
students::students() {
cout << "Name: ";
getline(cin, name);
cout << "Course: ";
getline(cin, course);
cout << "Number: ";
cin >> this->number;
cout << "Average: ";
cin >> this->average;
}
void students::list() {
cout << left << setw(11) << number;
cout << left << setw(30) << name;
cout << left << setw(30) << course;
cout << left << setw(10) << average << endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
//bool estudantes::compare(student a, student b) {
//
// if (a.number < b.number)
// return 1;
// else
// return 0;
//}
Made it selfcontained and fixed. I'll post and then aexplain as surely people will have closed the question too soon:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <string>
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
// friend bool operator<(students& left,students& right) { return
// left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
static bool compare(students const& a, students const& b);
};
students::students()
{
std::cout << "Name: "; getline(std::cin, name);
std::cout << "Course: "; getline(std::cin, course);
std::cout << "Number: "; std::cin >> this->number;
std::cout << "Average: "; std::cin >> this->average;
}
void students::list() {
std::cout << std::left << std::setw(11) << number;
std::cout << std::left << std::setw(30) << name;
std::cout << std::left << std::setw(30) << course;
std::cout << std::left << std::setw(10) << average << std::endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
class university {
private:
std::list<students> lstudents;
std::list<students>::iterator itstudents;
public:
university();
void setStudents(std::list<students> lstudents);
void registerStudent();
void list();
void average();
void sortStudents();
};
university::university() // constructor
{
std::string resp = "s";
int op;
bool out = true;
std::cout << "Enter Students:" << std::endl;
while (resp != "n") {
this->registerStudent();
std::cout << "Continue inserting? (s/n)" << std::endl;
std::cin >> out;
std::cin.ignore();
}
while (out) {
std::cout << "What you Want to do? (1- List Students 2- Sudent Average "
"3- Sort Students by Number 4- Leave)"
<< std::endl;
std::cin >> op;
switch (op) {
case 1: this->list(); break;
case 2:
this->average();
break;
case 3: this->sortStudents(); break;
case 4: out = false; break;
};
}
}
void university::setStudents(std::list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
std::cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
std::cout << std::left << std::setw(11) << "Number"
<< std::left << std::setw(30) << "Name"
<< std::left << std::setw(30) << "Course"
<< std::left << std::setw(10) << "Average";
std::cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//std::cout << "Total de pacientes:" << somatorio << std::endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
std::cout << "Average:" << average / sum << std::endl;
}
void university::sortStudents() {
lstudents.sort(&students::compare);
}
int main() {
university univ = university();
return 0;
}
Explanation
There were a number of issues.
students::compare was a non-static member function, meaning it can only be called on an instance of student. To have a 2-argument sort predicate as required, simply making it static can work
The implementation could be much more idiomatic:
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
That avoids the C-ism of using 1 as if it were true, and the useless if/else
You used std::sort but it requires random access iterators. std::list doesn't provide that. For that reason std::list::sort exists:
void university::sortStudents() {
lstudents.sort(&students::compare);
}
Among many other style issues:
don't using namespace std;
don't do side-effects in constructors?
error-check IO
avoid division by zero (e.g. in average()

c++ vector of structs inside class

hello all i am working on a school prject called inventory inquisitor. the specifications are as follows:
enter image description here
so far i have created a class in which contains a struct and a vector of this struct.
all im trying to do so far is get the class to display the struct just to know it works but when i compile it and run it nothing happens. here is the code. excuse whatever rookie mistakes i have made i am very new with classes, and vectors. thanks you in advance!
//Inventory Inquisitor.cpp
#include <iostream>
#include <string>
#include <cctype> //for toupper
#include <fstream>
#include <vector>
using namespace std;
class Inventory
{
private:
struct item
{
string Description = " ";
double Quantity = 0;
double Wholesalescost = 0;
double Retailcost = 0;
string Dateadded = " ";
};
vector<item> Inv;
public:
void Display();
};
void Inventory::Display()
{
Inv[0].Description = "english";
Inv[0].Quantity = 1;
Inv[0].Wholesalescost = 100;
Inv[0].Retailcost = 200;
Inv[0].Dateadded = "3/8/2018";
cout << Inv[0].Description << endl;
cout << Inv[0].Quantity << endl;
cout << Inv[0].Wholesalescost << endl;
cout << Inv[0].Retailcost << endl;
cout << Inv[0].Dateadded << endl;
}
int main()
{
Inventory inst1;
inst1.Display();
}
You have to put something into the vector before accessing it:
// Create an item
item i;
i.Description = "english";
i.Quantity = 1;
i.Wholesalescost = 100;
i.Retailcost = 200;
i.Dateadded = 3/8/2018;
// The vector is empty, size() == 0
// Add it to the vector
Inv.push_back(i);
// Now the vector has 1 item, size() == 1
// Now you can print it
cout << Inv.at(0).Description << endl;
cout << Inv.at(0).Quantity << endl;
cout << Inv.at(0).Wholesalescost << endl;
cout << Inv.at(0).Retailcost << endl;
cout << Inv.at(0).Dateadded << endl;
According to your assignment, you will most likely change to function to print an existing item. You will have another function to add items to the vector.
void Inventory::Display(int index)
{
// Print an item already in the vector
if (index >= 0 && index < Inv.size()) {
cout << Inv.at(index).Description << endl;
cout << Inv.at(index).Quantity << endl;
cout << Inv.at(index).Wholesalescost << endl;
cout << Inv.at(index).Retailcost << endl;
cout << Inv.at(index).Dateadded << endl;
}
}

Accessing variables in base class C++

Hi this is the header file for my base class Ranger, and in it I have protected variables fov_, usb_ ... that I wish to access with my getter functions, I have three child classes on this one.
Ranger.h
#ifndef RANGER_H
#define RANGER_H
using namespace std;
class Ranger
{
//private contructor prevents contruction of base class
Ranger();
public:
void setBaud(int baud);
virtual void setFOV(int fov) = 0;
void setSamp(int sam);
int getFOV();
int getBaud();
int getMaxRange();
int getUSB();
protected:
//protected variables that are each indivdualy owned by each sensor
int fov_;
int maxRange_;
int usb_;
int baud_;
int samp_;
double data[];
//protected contructors for the child classes to use to set fixed parameters
Ranger(int fov, int maxRange, int port);
Ranger(int maxRange, int port);
};
#endif // RANGER_H
This is my cpp file for the base class that includes the getter files, it just has a return of the portected variables.
Ranger::Ranger()
{
}
Ranger::Ranger(int fov, int maxRange, int port)
{
fov_ = fov;
maxRange_ = maxRange;
usb_ = port;
}
Ranger::Ranger(int maxRange, int port)
{
maxRange_ = maxRange;
usb_ = port;
}
void Ranger::setBaud(int baud)
{
switch(baud)
{
case 0: baud_ = 38400; break;
case 1: baud_ = 115200; break;
default: baud_ = 38400; break;
}
}
void Ranger::setSamp(int sam)
{
samp_ = sam;
}
int Ranger::getFOV()
{
return fov_;
}
int Ranger::getBaud()
{
return baud_;
}
int Ranger::getMaxRange()
{
return maxRange_;
}
int Ranger::getUSB()
{
return usb_;
}
And in my main I want to access the protected variables from the base class to prevent re writting code, so each childs variables are protected in the base class. I try to access these by las.getFOV() but I get a segmentation fault error meaning I don't have access to them, and I don't quite understand why.
main.cpp
int main( int argc, char ** argv)
{
Laser las;
int baud;
cout << "Baud:" << endl;
cout << "0 - 38400" << endl;
cout << "1 - 115200" << endl;
cin >> baud;
las.setBaud(baud);
cout << "Baud for Lazer sensor is "+las.getBaud() << endl;
cout << "Lazer sensor created..." << endl;
cout << "Lazer's FOV: " + las.getFOV() << endl;
cout << "Lazer's Max Range: " + las.getMaxRange() << endl;
cout << "Lazer's Port: " + las.getUSB() << endl;
Radar rad;
int baud2;
cout << "Baud:" << endl;
cout << "0 - 38400" << endl;
cout << "1 - 115200" << endl;
cin >> baud2;
rad.setBaud(baud2);
cout << "Baud for Radar sensor is "+rad.getFOV() << endl;
int fov;
cout << "Feild of View Of Radar:" << endl;
cout << "0 - 20 degrees" << endl;
cout << "1 - 40 degrees" << endl;
cin >> fov;
rad.setFOV(fov);
cout << "FOV is set to " + rad.getFOV() << endl;
cout << "Radar sensor created..." << endl;
cout << "Radar's FOV: ' " + rad.getFOV() << endl;
cout << "Radar's Max Range: " + rad.getMaxRange() << endl;
cout << "Radar's Port: " + rad.getUSB() << endl;
Sonar son;
//rad.setFOV(user);
}
and here is one of the child class's cpp file for reference (Lazer)
laser.cpp
#include "laser.h"
Laser::Laser() : Ranger(180,8,0)
{
};
void Laser::setFOV(int fov)
{
fov_ = fov;
}
laser.h
#ifndef LASER_H
#define LASER_H
#include "ranger.h"
#include "rng.h"
class Laser : public Ranger
{
public:
Laser();
void setFOV(int fov);
};
#endif // LASER_H
Thanks everyone who commented, I understand I put way too much code to help you guys out, sorry about that I'll know for next time, and thankyou to letting me know the difference between the errors, I've done more research and found that the issue was when I was printing it out you can't use operators like:
cout<<""+function()<<endl;
Instead you need to separate the functions from the array like so:
cout<<""<<function()<<endl;
Thanks guys.

Pointer to incomplete class type is not allowed

For some reason I cannot use functions attached to the object I want to use. I added a comment to the line that is not working. As an error I get "Error; pointer to incomplete class type is not allowed" Please help
This is code in dokter.ccp
int counter = 0;
for (list<Wielrenner*>::iterator it = wielrenners.begin(); it != wielrenners.end(); it++){
Wielrenner* wielrennerOB = *it;
cout << "\nID: " << counter;
cout << "List size: " << persons.size() << endl;
wielrennerOB->print(); // This is not working
counter++;
}
This is code in wielrenner.h
#ifndef WIELRENNER_H_
#define WIELRENNER_H_
//#include <fstream>
#include "persoon.h"
#include "Onderzoek.h"
class Wielrenner :
public Persoon
{
public:
Wielrenner(string, string, Adres, string, Datum, Datum, string, int, float, float, float,list<Onderzoek>* );
~Wielrenner(void);
int getLengte() const;
float getGewicht() const;
float getVo2max() const;
float getMaxVermogen() const;
list<Onderzoek> getOnderzoekenList();
void setLengte(int);
void setGewicht(float);
void setVo2max(float);
void setMaxVermogen(float);
void voegOnderzoekToeList(Onderzoek);
void showOnderzoeksList();
void setOnderzoeksLijst(list<Onderzoek>&);
void print();
void printFile(ofstream&);
private:
int lengte;
float gewicht;
float vo2max;
float maxVermogen;
list<Onderzoek> onderzoeken;
};
#endif /* WIELRENNER_H_ */
code in wielrenner.CCP
using namespace std;
#include <string>
#include "Wielrenner.h"
/*
#include "Onderzoek.h"
*/
Wielrenner::Wielrenner(string voornaam, string achternaam, Adres adres, string telefoon, Datum datumInDienst, Datum geboorteDatum,
string persoonType, int lengte, float gewicht, float vo2max, float maxVermogen,list<Onderzoek>* onderzoeken)
: lengte(lengte),
gewicht(gewicht),
vo2max(vo2max),
maxVermogen(maxVermogen),
Persoon(voornaam, achternaam, adres, telefoon, datumInDienst, geboorteDatum, persoonType)
{
}
Wielrenner::~Wielrenner(void)
{
}
//setten van gegevens
void Wielrenner::setLengte(int newLengte){
lengte = newLengte;
}
void Wielrenner::setGewicht(float newGewicht){
gewicht = newGewicht;
}
void Wielrenner::setVo2max(float newVo2max){
vo2max = newVo2max;
}
void Wielrenner::setMaxVermogen(float newMaxVermogen){
maxVermogen = newMaxVermogen;
}
void Wielrenner::voegOnderzoekToeList(Onderzoek newOnderzoek){
onderzoeken.push_back(newOnderzoek);
}
void Wielrenner::showOnderzoeksList(){
int teller=0;
for (list<Onderzoek>::iterator it = onderzoeken.begin(); it != onderzoeken.end(); it++){
Onderzoek onderzoekOB = *it;
cout << teller << " - ";
onderzoekOB.print();
teller++;
}
}
void Wielrenner::setOnderzoeksLijst(list<Onderzoek>& newOnderzoeksLijst){
onderzoeken = newOnderzoeksLijst;
}
void Wielrenner::print(){
cout << "(" << persoonID << ") Persoon: " << endl;
cout << persoonType << endl;
cout << voornaam << " " << achternaam << endl;
adres.print();
cout << telefoon << endl;
cout << "Datum in dienst: ";
datumInDienst.print();
cout << "Geboortedatum: ";
geboorteDatum.print();
cout << "> Extra wielrenner gegevens: " << endl;
cout << "Lengte: " << lengte << endl;
cout << "Gewicht: " << gewicht << endl;
cout << "vo2max: " << vo2max << endl;
cout << "maxVermogen: " << maxVermogen << endl;
}
void Wielrenner::printFile(ofstream &myfile){
myfile << persoonID << "\n";
myfile << persoonType << "\n";
myfile << voornaam << " " << achternaam << "\n";
adres.printFile(myfile);
myfile << telefoon << "\n";
datumInDienst.printFile(myfile);
geboorteDatum.printFile(myfile);
myfile << lengte << "\n";
myfile << gewicht << "\n";
myfile << vo2max << "\n";
myfile << maxVermogen << "\n";
}
// returnen van gegevens
int Wielrenner::getLengte() const{
return lengte;
}
float Wielrenner::getGewicht() const{
return gewicht;
}
float Wielrenner::getVo2max() const{
return vo2max;
}
float Wielrenner::getMaxVermogen() const{
return maxVermogen;
}
list<Onderzoek> Wielrenner::getOnderzoekenList(){
return onderzoeken;
}
An "incomplete class" is one declared but not defined. E.g.
class Wielrenner;
as opposed to
class Wielrenner
{
/* class members */
};
You need to #include "wielrenner.h" in dokter.ccp
One thing to check for...
If your class is defined as a typedef:
typedef struct myclass { };
Then you try to refer to it as struct myclass anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:
typedef struct mystruct {}...
struct mystruct *myvar = value;
Instead use...
mystruct *myvar = value;
Common mistake.
You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:
namespace X
{
namespace Y
{
class A;
void func(A* a) { ... } // incomplete type here!
}
}
...but, in class A was defined like this:
namespace X
{
class A { ... };
}
Thus, A was defined as X::A, but I was using it as X::Y::A.
The fix obviously is to move the forward reference to its proper place like so:
namespace X
{
class A;
namespace Y
{
void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
}
}
The problem also occurs when header files are not included explicitly where they are needed, but implicitly through other heading files.
I came accross the same problem and solved it by checking my #includes.
If you use QKeyEvent you have to make sure that you also include it.
I had a class like this and my error appeared when working with "event"in the .cpp file.
myfile.h
#include <QKeyEvent> // adding this import solved the problem.
class MyClass : public QWidget
{
Q_OBJECT
public:
MyClass(QWidget* parent = 0);
virtual ~QmitkHelpOverlay();
protected:
virtual void keyPressEvent(QKeyEvent* event);
};
Check out if you are missing some import.