I have a class Project and each Project can have different tasks.
Project.h:
#pragma once
#include "Task.h"
#include <vector>
using namespace std;
class Project
{
private:
vector<Task> Tasks;
public:
Project::Project(int inleesgetal);//constructor
vector<Task> GetTasks();
};
Project.cpp:
#include "Project.h"
#include <string>
#include <vector>
Project::Project(int inleesgetal)
{
//constructor
Tasks.resize(Numbertasks);
}
vector<Task> Project::GetTasks()
{
return Tasks;
}
Task.h:
#pragma once
#include <vector>
using namespace std;
class Task
{
private:
//Info:
int StartTime_Solo;
public:
Task(); //constructor
void SetStartTime_Solo(int st_s);
int GetStartTime_Solo();
};
Task.cpp:
#include "Task.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
Task::Task()
{
//constructor
StartTime_Solo = 0;
}
int Task::GetStartTime_Solo()
{
return StartTime_Solo;
}
void Task::SetStartTime_Solo(int st_s)
{
StartTime_Solo = st_s;
}
main:
#include <iostream>
#include <vector>
#include "Task.h"
#include "Project.h"
using namespace std;
int main()
{
Project Project1(6);
Project1.GetTasks()[2].SetStartTime_Solo(55);
cout << "test:" << Project1.GetTasks()[2].GetStartTime_Solo();
return 0;
}
Now when I try to set the 3rd task of Project1 to a starttime of 55 and then print the start time out it still gives me 0 as a result.
Why is this? And how can I change my code so it actually sets the starttime to 55?
vector<Task> GetTasks();
should be
const vector<Task>& GetTasks() const;
vector<Task>& GetTasks();
And so with definitions:
vector<Task> Project::GetTasks()
{
return Tasks;
}
should be:
const vector<Task>& Project::GetTasks() const { return Tasks; }
vector<Task>& Project::GetTasks() { return Tasks; }
The problem is that you are returning a copy of the vector<Task> from the GetTasks function. You then modify this copy and throw it away right afterwards. The internal member of Project is not changed.
If you return by reference like this:
vector<Task>& GetTasks();
Then you are basically returning something that points to the internal vector, and so when you modify it, you actually modify the member data of your class.
Related
I am new to C++, and I am currently working on 2 different projects within the some solution in C++ with VSC and I am encountering the error "A class-qualified name is required"; I have created a custom class in a file inside a namespace like so in project Stock:
//in file Stock.h, project Stock
#pragma once
#include "CandleStick.h"
#include "StockRecord.h"
#include "MarketQue.h"
#include <string>
#include <vector>
namespace Stock {
class Stock {
private:
std::string s_stockID;
MarketQue* s_topCur;
StockRecord s_stockRecord;
std::vector<CandleStick> s_candleSticks;
unsigned int s_totalVol;
public:
Stock(const std::string&, MarketQue&, std::vector<unsigned int>&, unsigned int); //stockID, s_topCurPrice_B, s_topCurPrice_S, s_topCurVol_B, s_topCurVol_S, cs_interval, total_vol
void updateStock(int);
~Stock();
protected:
};
}
//in file Stock.cpp, project Stock
#include "Stock.h"
Stock::Stock::Stock(const std::string& stockID, MarketQue& topPrices, std::vector<unsigned int>& csInterval, unsigned int totalVol)
:s_stockID(stockID), s_topCur(&topPrices), s_stockRecord(StockRecord(topPrices.mq_size)), s_totalVol(totalVol) {
s_candleSticks.reserve(csInterval.size());
for (unsigned int i = 0; i < csInterval.size(); i++) {
s_candleSticks.emplace_back(topPrices.mq_topPrice_S[0], topPrices.mq_topPrice_B[0], csInterval[i]);
}
};
void Stock::Stock::updateStock(int totalVol) {
s_totalVol = totalVol;
s_stockRecord.updateStockRecord(*s_topCur);
for (unsigned int i = 0; i < s_candleSticks.size(); i++) {
s_candleSticks[i].updateCandleStick((s_topCur->mq_topPrice_B)[0], (s_topCur->mq_topPrice_S)[0]);
}
}
Stock::Stock::~Stock() {};
I have successfully linked the 2 projects together (I think, tested it in the main function with a file called App.cpp in project Market):
//in file App.cpp, project Market
#include "Stock.h"
#include "MarketQue.h"
#include <string>
#include <array>
#include <vector>
int main() {
//initializing
const std::string stockID = "001";
Stock::MarketQue topPrices(3);
std::vector<float> topCurPrice_B = { 3,2,1 };
std::vector<float> topCurPrice_S = { 4,5,6 };
topPrices.mq_topPrice_B = topCurPrice_B;
topPrices.mq_topPrice_S = topCurPrice_S;
std::vector<unsigned int> topCurVol_B = { 10,11,12 };
std::vector<unsigned int> topCurVol_S = { 13,14,15 };
topPrices.mq_topVol_B = topCurVol_B;
topPrices.mq_topVol_S = topCurVol_S;
std::vector<unsigned int> cs_Interval = { 100,300,1000 };
unsigned int totalVol= 3+2+1+4+5+6;
Stock::Stock first_stock(stockID, topPrices, cs_Interval, totalVol);
totalVol = 100;
first_stock.updateStock(totalVol);
//testing update
topCurPrice_B = { 13,12,11 };
topCurPrice_S = { 14,15,16 };
topCurVol_B = { 110,111,112 };
topCurVol_S = { 113,114,115 };
topPrices.mq_topPrice_B = topCurPrice_B;
topPrices.mq_topPrice_S = topCurPrice_S;
topPrices.mq_topVol_B = topCurVol_B;
topPrices.mq_topVol_S = topCurVol_S;
}
However, when I try to use this class(Stock::Stock) as a member inside of another class (in project Market), I received the error mentioned above ("A class qualified name is required");
I first did this:
//in file Market.h, project Market
#pragma once
#include "Stock.h"
#include <string>
#include <vector>
namespace Market {
class Market {
private:
std::string marketID;
std::vector<Stock::Stock> stock; //received error
Stock::Stock stock;
public:
Market();
void updateStock();
~Market();
protected:
};
}
At this point i figured it might be because of the namespace Market making it Market::Stock::Stock and i decided to remove the namespace Market:
//in file Market.h, in project Market
#pragma once
#include "Stock.h"
#include <string>
#include <vector>
class Market {
private:
std::string marketID;
std::vector<Stock::Stock> stock;
public:
Market();
void updateStock();
~Market();
protected:
};
I'd like to ask how to fix this problem, and if possible can someone explain to me what is happenning to the code that caused the error?
Thank you very much for your time.
I am new to c++ . The program doesn't compile i am using Xcode. It doesn't give me any error. It just doesn't compile which's weird. Thanks for the help!
I am using 3 files as you can see. I think. there's a problem with the implementation that i can not figure out, if you have any suggestion for a better IDE that Xcode than would be helpful.
Thanks again
Car.cpp
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
void Car:: setMaker(string m)
{
maker=m;
}
string Car:: getMaker()
{
return maker;
}
void Car:: setModel(int m)
{
model=m;
}
int Car:: getModel()
{
return model;
}
Car.h
#ifndef _CAR_H;
#define _CAR_H;
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Car
{
private:
string maker;
int model;
public:
void setMaker(string m);
string getMaker();
void setModel(int m);
int getModel();
};
#endif
main.cpp
#include <iostream>
#include "Car.cpp"
#include "Car.h"
using namespace std;
int main ()
{
Car c1;
c1.setMaker("BMW");
c1.getMaker();
return 0;
}
I'm developing a simulation game in cpp using Visual Studio 2017 for School and in the development phase I got stuck in this situation.
So, what I did was create a new project to try and recreate that issue in the simplest form, so that it would be easier to debug.
Below is the main file and all the associated source codes:
main.cpp
#include "header.h"
#include "Vehicle.h"
#include "Car.h"
int main() {
Vehicle v;
v.addCar(1);
v.addCar(2);
v.addCar(3);
cout << v.getCars()[1].id << endl;
v.getCars()[1].id = 99;
cout << v.getCars()[1].id << endl;
system("pause");
return 0;
}
header.h
#ifndef CLUSTE2R_H
#define CLUSTE2R_H
#pragma once
#include <iostream>
#include <vector>
using namespace std;
#endif
Car.h
#ifndef CLUSTE1R_H
#define CLUSTE1R_H
#pragma once
#include "Vehicle.h"
using namespace std;
class Car : public Vehicle
{
public:
int id;
Car(int id);
~Car();
};
#endif
Car.cpp
#include "Car.h"
Car::Car(int id)
{
this->id = id;
}
Car::~Car()
{
}
Vehicle.h
#ifndef CLUSTER_H
#define CLUSTER_H
#pragma once
#include <vector>
//#include "Car.h"
class Car;
using namespace std;
class Vehicle
{
private:
vector<Car> cars;
public:
Vehicle();
~Vehicle();
vector<Car> getCars();
void addCar(int id);
};
#endif
Vehicle.cpp
#include "Vehicle.h"
#include "Car.h"
#include <vector>
using namespace std;
//class Car;
Vehicle::Vehicle()
{
}
Vehicle::~Vehicle()
{
}
vector<Car> Vehicle::getCars()
{
return this->cars;
}
void Vehicle::addCar(int id)
{
Car c(id);
cars.reserve(cars.size() + 1);
cars.push_back(c);
}
So, what I'm trying to do is to get the following output:
2 \n 99
This is what I'm getting:
2 \n 2
What am I doing wrong? I believe the issue is associated with the main.cpp file. But I'm not quite sure how to achieve what I want in any other way...
Currently, you are returning a new instance of a vector when you call getCars() function from your Vehicle, this means that all changes to the vector will not be applied to the original vector in the class.
To fix this you could just return a reference of the vector(changing the vector<Car> getCars(); to std::vector<Car>& getCars()).
You could also make a local copy of the vector and then setting the vector to the class.
I want to pass my vector "myStaffs" from Team Class by reference to Manage Class because I want to manipulate the data of staffs and sort them. How do I pass it by reference?
Header Staff
#ifndef STAFF_H
#define STAFF_H
#include <vector>
#include <cstdlib>
#include <ctime>
#include <string>
class Staff
{
public:
Staff();
Staff(int, int, int, int);
~Staff();
static int genRanNum(int);
static Staff* createStaff(int);
const int getSize();
private:
int staSkills1,staSkills2,staSkills3;
int staId;
//int staDeptAsigned;
//std::string staName;
};
#endif
CPP Staff
#include "Staff.h"
#include <iostream>
using namespace std;
Staff::Staff():
staId(0),
staSkills1(0),
staSkills2(0),
staSkills3(0)
{
}
Staff::Staff(int id, int s1, int s2, int s3):
staId(id),
staSkills1(s1),
staSkills2(s2),
staSkills3(s3)
{
}
Staff *Staff::createStaff(int s)
{
Staff *staff = new Staff();
staff->staId = s;
staff->staSkills1 = genRanNum(10);
staff->staSkills2 = genRanNum(10);
staff->staSkills3 = genRanNum(10);
return staff;
}
int Staff::genRanNum(int num)
{
return 1+(rand()%num);
}
Staff::~Staff()
{
}
Header Team
#ifndef TEAM_H
#define TEAM_H
#include "Staff.h"
#include <vector>
#include <iostream>
using std::vector;
class Team: public Staff
{
public:
Team();
~Team();
private:
vector<Staff *> myStaffs;
};
#endif // TEAM_H
CPP Team
#include "Team.h"
const int SIZE = 30;
Team::Team():
myStaffs(SIZE)
{
for(int iStaff = 0; iStaff <= SIZE; iStaff++)
{
myStaffs[iStaff] = createStaff(iStaff);
}
}
Team::~Team()
{
}
Header Manage
#ifndef OPTIONS_H
#define OPTIONS_H
#include "Team.h"
#include <vector>
#include <iostream>
using std::vector;
class Manage
{
public:
Manage();
~Manage();
private:
// vector
};
CPP Manage
#include "Manage.h"
Manage::Manage()
{
}
Manage::~Manage()
{
}
#endif
Its simple you pass it as you would pass any other object by reference
int sortEmployee(std::vect<Staff *> &staffList> {
// ... code to sort Employee
}
and you can call it like below
vector<Staff *> myStaffs
result = sortEmployee(myStaffs);
It's as simple as
#include <vector>
void myVectorManglingFun(std::vector<Staff *> &myStaff) //notice the &
{
//do something here
}
If you don't need to modify the vector, then always use a const reference.
void myVectorReadingFun(const std::vector<Staff *> &myStaff)
How do I execute a member's function by passing the object and the member's function to another function in c++. I do understand the answer to my question is out there; however, I do not know what this is called. So far I created 2 files, exeFunc.h and exeFunc.cpp. Their code consist of:
exeFunc.h
/*
File: exeFunc.h
Header file for exeFunc Library.
*/
#ifndef EXEFUNC_H
#define EXEFUNC_H
#include "mbed.h"
#include "msExtensions.h"
#include "cfExtensions.h"
#include <map>
class exeFunc
{
public:
exeFunc(msExtensions &msExt, cfExtensions &cfExt);
private:
void _splitFuncFromCmd();
void _attachCallback();
msExtensions &_msExt;
cfExtensions &_cfExt;
//FunctionPointer _p;
};
#endif
exeFunc.cpp
/*
File: exeFunc.cpp
Execute functions in other Sensor libraries/classes
Constructor
*/
#include "mbed.h"
#include "ConfigFile.h"
#include "msExtensions.h"
#include "cfExtensions.h"
#include "exeFunc.h"
#include <map>
#include <string>
using namespace std;
exeFunc::exeFunc(msExtensions &msExt, cfExtensions &cfExt) : _msExt(msExt), _cfExt(cfExt)
{
//_cfExt.checkConfigForFirstStart();
//_p.attach(&_cfExt, &cfExtensions::checkConfigForFirstStart);
//_p.call();
}
void exeFunc::_splitFuncFromCmd()
{
}
void exeFunc::_attachCallback()
{
}
I wrote a completed example, may helps
class MyClass
{
public:
MyClass(int b)
:_b(b)
{
}
int Foo(int a)
{
return a * _b;
}
int _b;
};
typedef int (MyClass::*MFP)(int);
int get_result(MyClass* obj, MFP mfp)
{
int r = (obj->*mfp)(5); // 30
return r;
}
int _tmain(int argc, _TCHAR* argv[])
{
MFP mfp = &MyClass::Foo;
MyClass m(6);
get_result(&m, mfp);
return 0;
}
You call it by another function.if you have an independent function.
To be honesty your question is not completely clear.However :
int F(int,int,int);
int g();
//main scope
F(g(),a,b)