Pieter Pieter - 1 month ago 16
C++ Question

setter and getter /classes

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?

Answer
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; }
Comments