Im on year 10 and our teacher wants us to create an original project and using pointers
What I want to do is to create Members and be able to sort the members by there names and print them
When I run my code it says Invalid Access
Team.h
#ifndef TEAM_H
#define TEAM_H
#include "Staff.h"
#include <vector>
#include <iostream>
using std::vector;
class Team: public Staff
{
public:
Team();
~Team();
vector<Staff *> &getVector();
private:
vector<Staff *> myStaffs;
};
#endif // TEAM_H
Team.cpp
Team::Team()
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
myStaffs[iStaff] = createStaff(iStaff);
}
}
vector<Staff*>& Team::getVector()
{
return myStaffs;
}
Command class will do the sorting of team and print all team members
Command.cpp
void Command::printStaffs(vector<Staff*>&myStaffs)
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
std::cout << "Staff ID number: "<< myStaffs[iStaff]->getStaId() << std::endl
<< "Staff Skills 1: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< "Staff Skills 2: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< "Staff Skills 3: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< std::endl;
}
}
Command.h
#ifndef CommandH
#define CommandH
#include "Team.h"
#include <vector>
#include <iostream>
using std::vector;
class Command: public Team
{
public:
Command(){}
~Command(){}
void sortVector(vector<Staff* >&vectorTemp);
void printStaffs(vector<Staff* >&);
private:
vector<Staff *> vectEmployee;
};
//--------------------------------------------------------------------------
#endif
main.cpp
#include <iostream>
#include <conio.h>
#include "Team.h"
#include "Command.h"
int main()
{
Team t;
Command c;
c.printStaffs(t.getVector());
getch();
return 0;
}
Staff.h
#ifndef STAFF_H
#define STAFF_H
#include <cstdlib>
#include <ctime>
#include <string>
using std::rand;
class Staff
{
public:
Staff();
~Staff();
static Staff* createStaff(int); // creates staffs
int** getStaSkill();
int getStaId(); // returns Staff ID
static int genRanNum(int); //Generate random number
private:
int *staSkill[3];
int staId;
//int staDeptAsigned;
};
#endif
Staff.cpp
#include "Staff.h"
Staff::Staff()
{
*staSkill = new int[3];
}
Staff *Staff::createStaff(int s)
{
Staff *staff = new Staff();
staff->staId = s;
*(staff->staSkill[0]) = genRanNum(10);
*(staff->staSkill[1]) = genRanNum(10);
*(staff->staSkill[2]) = genRanNum(10);
return staff;
}
int** Staff::getStaSkill()
{
return staSkill;
}
int Staff::getStaId()
{
return staId;
}
int Staff::genRanNum(int num)
{
return 1 +(std::rand()%num);
}
Staff::~Staff(){}
When you construct a Team, you have the following constructor:
Team::Team()
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
myStaffs[iStaff] = createStaff(iStaff);
}
}
However, myStaffs is a member of Team and gets default constructed as empty, so nothing happens here since myStaffs.size() == 0.
Calling printStaffs on this Team::getVector() will correctly inform you that the vector is empty:
int main()
{
Command c;
Team t; // t.myStaffs will be empty
c.printStaffs(t.getVector()); // passes an empty vector to printStaffs
return 0;
}
You might want to pass a number to your Team constructor to create that many staffs:
Team::Team(int number_of_staff)
{
for(unsigned int iStaff = 0; iStaff < number_of_staff; iStaff++)
{
myStaffs.push_back(createStaff(iStaff));
}
}
int main()
{
Command c;
Team t(5); // t.myStaffs will contain 5 staff members
c.printStaffs(t.getVector()); // passes vector of 5 staff
return 0;
}
Related
Or is there a way to get ResponseState::EncoderTag out of class ResponseState?
The code is shown below
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class MirroredMsgRespState
{
public:
virtual ~MirroredMsgRespState(){}
virtual uint32_t encoderTag() const = 0;
};
template<typename RespMsgT, uint32_t EncoderTag>
class ErrorAndEntryResponseState : public MirroredMsgRespState
{
public:
uint32_t encoderTag() const override
{
return EncoderTag;
}
};
using ResponseState = ErrorAndEntryResponseState<int, 48>;
int main()
{
unique_ptr<MirroredMsgRespState> myResp = make_unique<ResponseState>();
cout << myResp->encoderTag() << endl; // func 1
cout << ResponseState::encoderTag() << endl; // func 2
return 0;
}
The current implementation causes the second call to report an error
You could add a static method:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class MirroredMsgRespState
{
public:
virtual ~MirroredMsgRespState(){}
virtual uint32_t encoderTag() const = 0;
};
template<typename RespMsgT, uint32_t EncoderTag>
class ErrorAndEntryResponseState : public MirroredMsgRespState
{
public:
static uint32_t getEncoderTag()
{
return EncoderTag;
}
uint32_t encoderTag() const override
{
return getEncoderTag();
}
};
using ResponseState = ErrorAndEntryResponseState<int, 48>;
int main()
{
unique_ptr<MirroredMsgRespState> myResp = make_unique<ResponseState>();
cout << myResp->encoderTag() << endl; // func 1
cout << ResponseState::getEncoderTag() << endl; // func 2
return 0;
}
class A
{
int id;
public:
A (int i) { id = i; }
void show() { cout << id << endl; }
};
int main()
{
A a[2];
a[0].show();
a[1].show();
return 0;
}
I get an error since there is no default constructor.However thats not my question.Is there a way that ı can send parameters when defining
A a[2];
A good practice is to declare your constructor explicit (unless it defines a conversion), especially if you have only one parameter. Than, you can create new objects and add them to your array, like this :
#include <iostream>
#include <string>
class A {
int id;
public:
explicit A (int i) { id = i; }
void show() { std::cout << id << std::endl; }
};
int main() {
A first(3);
A second(4);
A a[2] = {first, second};
a[0].show();
a[1].show();
return 0;
}
However, a better way is to use vectors (say in a week you want 4 objects in your array, or n object according to an input). You can do it like this:
#include <iostream>
#include <string>
#include <vector>
class A {
int id;
public:
explicit A (int i) { id = i; }
void show() { std::cout << id << std::endl; }
};
int main() {
std::vector<A> a;
int n = 0;
std::cin >> n;
for (int i = 0; i < n; i++) {
A temp(i); // or any other number you want your objects to initiate them.
a.push_back(temp);
a[i].show();
}
return 0;
}
I define a ThreadPoolclass, and it has a memeber: std::array<Worker, ThreadNum> Workerlist.
The code is as follows:
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <pthread.h>
#include <memory>
#include "Worker.h"
#include <vector>
#include <array>
const int MAX_THREAD_NUM = 16;
class ThreadPool
{
private:
const unsigned int ThreadNum;
std::shared_ptr<EventLoop> MainLoop;
std::array<std::shared_ptr<Worker>, ThreadNum> WorkerList;
std::array<std::shared_ptr<EventLoop>, ThreadNum> EventLoopList;
unsigned int NextLoopIndex;
public:
ThreadPool(std::shared_ptr<EventLoop> loop, int threadNum = 12);
~ThreadPool();
void RunThreadPool();
std::shared_ptr<EventLoop> GetNextEventLoop();
}
#endif
ThreadPool.cpp
ThreadPool::ThreadPool(std::shared_ptr<EventLoop> loop, int threadNum): MainLoop(loop), ThreadNum(threadNum), NextLoopIndex(0)
{
if (ThreadNum<=0 || ThreadNum> MAX_THREADS)
{
LOG << "The num of threads is out of range.\n";
}
}
ThreadPool::~ThreadPool() {}
void ThreadPool::RunThreadPool()
{
WorkerList.fill(std::make_shared<Worker>());
for (auto i = 0; i < ThreadNum; i++)
{
EventLoopList.at(i) = WorkerList.at(i)->ReturnEventLoopPtr();
}
}
std::shared_ptr<EventLoop> ThreadPool::GetNextEventLoop()
{
if (!EventLoopList.empty())
{
std::shared_ptr<EventLoop> nextLoop = EventLoopList[NextLoopIndex];
NextLoopIndex = (NextLoopIndex + 1) % ThreadNum;
return nextLoop;
}
return;
}
The error message is:
invalid use of data member ThreadPool::ThreadNum
In my opinion, the template parameter ThreadNum should be a constant, but now I need to infer its value when the class is constructed. Any solutions? Thank you very much.
I'm working on a multiple inheritance exercise and I'm running into a strange error. My code is not returning the correct information to the console. It is just outputting zero, I have checked multiple times in my code and I can't seem to find anything obviously wrong. I'm fairly new to C++ so any help I would appreciate it, in addition to any other critique.
The console will output
Maverick
South station
50 - passengers, is ok
40 - speed
0 - it is supposed to take distance/mph and output 2.6 in this case, but is returning nothing.
MBTA.cpp
#include "MBTA.h"
//objects
transportation Dest;
MBTA::MBTA()
{
}
MBTA::MBTA(string strIn, string strInTransport, int iIn, int distIn, int eIn)
{
setTrain(strIn);
//Destination
Dest.setTransport(strInTransport);
//set passengers
setPass(iIn);
Dest.setMilesToDest(distIn);
engine.setMPH(eIn);
//outputs train information
printTrainDestinationHours();
//used printf as I was running into issue with using cout here
//cout << " I am going to ";
printf("I am going to %s\n", Dest.getTransport().c_str());
//uses engine stats function
cout << "I go " << engine.getMPH() << endl;
printf("It will take me %.2f hours to arrive", redline.getTotal());
}
void MBTA::setTravelDist(int iIn)
{
double destdistance = Dest.getDist();
double trainMPH = engine.getMPH();
//this divides miles by MPH, this might return a float
redline.setTotal(50, 10);
}
MBTA::~MBTA()
{
}
MBTA.H
#pragma once
#include "train.h"
class MBTA :
public train
{
public:
engine engine;
train redline;
MBTA();
//train, destination, passengers, traveldist, speed
MBTA(string, string, int, int, int);
void setTravelDist(int);
//double getTotal();
//uses engine stats function
//double total = 0;
~MBTA();
};
Train.cpp
#include "train.h"
#include <iostream>
#include <cstdio>
#include <cmath>
using std::string;
using std::cout;
using std::endl;
//object member for transport
transportation tTrain;
train::train()
{
}
void train::printTrainDestinationHours()
{
printf("\n\nTrain type: %s\n", getTrain().c_str());
//passengers
printf("I have %d passengers\n", getPass());
}
void train::setPass(int iIn)
{
passengers = iIn;
}
int train::getPass()
{
return passengers;
}
void train::setTrain(string strIn)
{
trainName = strIn;
}
string train::getTrain()
{
return trainName;
}
void train::setTotal(int aIn, int bIn)
{
//dist / mph
total = aIn / bIn;
}
double train::getTotal()
{
return total;
}
train::~train()
{
}
Train Header
#pragma once
#include <iostream>
#include <cstdio>
using std::string;
using std::cout;
using std::endl;
#include "engine.h"
#include "transportation.h"
class train : public transportation
{
public:
train();
void printTrainDestinationHours();
//set and get destination
//num of pass
void setPass(int);
int getPass();
//train
void setTrain(string);
string getTrain();
//distance
void setTotal(int, int);
double getTotal();
~train();
private:
engine engineStats;
int total = 0;
string trainName = "";
string destination = "";
int passengers = 0;
};
engine.cpp
#include "engine.h"
engine::engine()
{
}
void engine::setMPH(int iIn)
{
MPH = iIn;
}
int engine::getMPH()
{
return MPH;
}
engine::~engine()
{
}
engine header
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
'''
transportation cpp
'''
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
transportation header
#include "transportation.h"
transportation::transportation()
{
}
void transportation::setTransport(string strIn)
{
destination = strIn;
}
string transportation::getTransport()
{
return destination;
}
void transportation::setMilesToDest(int iIn)
{
MilesToDestination = iIn;
}
int transportation::getDist()
{
return MilesToDestination;
}
transportation::~transportation()
{
}
main file
#include <iostream>
using std::string;
using std::cout;
using std::endl;
using std::cin; //for ignore
#include "challenger.h"
#include "MBTA.h"
#include "plane.h"
int main()
{
//object composition of vehicle type
// vehicle type location, passengers, MPH , distance
challenger SRT8707("Boston", 2, 100, 200);
plane boeing("boeing", "houston", 50, 500, 300);
MBTA redline("Maverick", "South station", 50, 100, 40);
//pause and blank line
cout << endl << endl;
cin.ignore();
}
I am new to classes and am having a lot of difficulty with the constructors. I have two constructors for a business class and whenever I attempt to create a business object or do anything with the business object I immediately Seg Fault. The business class interacts with an additional class called Customer. If anyone could offer any help I would greatly appreciate it.
Business.h
#ifndef BUSINESS_H
#define BUSINESS_H
#include <iostream>
#include <string>
#include "customer.h"
using namespace std;
class Business
{
public:
Business();
Business(string name, float cash);
void printData() const;
void addCustomer(Customer newCustomer);
void make_a_sale();
private:
string businessName;
float cashInReg;
string itemArray[10];
Customer custInBus[10];
short numOfItems;
short numOfCustom;
};
#endif
Business.cpp
#include "business.h"
#include <iostream>
#include <cstdlib>
using namespace std;
Business::Business(): businessName("Business"), cashInReg(0), numOfItems(0),
numOfCustom(0) {}
Business::Business(string name, float cash) : businessName(name),
cashInReg(cash), numOfCustom(0) {}
void Business::printData() const
{
cout << businessName <<endl;
for (int i=0; i<numOfCustom; i++)
{
cout << "\t Customer Name: " << custInBus[i].getName() <<endl;
}
for (int i=0; i<numOfItems; i++)
{
cout << "\t Item list: " <<itemArray[i] <<endl;
}
}
void Business::addCustomer(Customer newCustomer)
{
custInBus[numOfCustom-1] = newCustomer;
numOfCustom++;
}
void Business::make_a_sale()
{
int randomItem;
int currCustomer=0;
while (currCustomer < numOfCustom)
{
randomItem = rand() %tempItems;
custInBus[currCustomer].purchase(tempArray[randomItem]);
currCustomer ++;
}
}
void Business::addCustomer(Customer newCustomer)
{
custInBus[numOfCustom] = newCustomer;
//use numOfCustom instead of numOfCustom-1
numOfCustom++;
}