Vector/Array inside Object, Holding Objects of Another Class

天大地大妈咪最大 提交于 2019-12-25 17:21:56

问题


I am trying to store either the objects of a base class (employee), or pointers to the objects inside a vector/array in another class (finance) object. The number of employee objects depends on the user, so it needs to work dynamically. So far I have this:

finance.h

#ifndef FINANCE
#define FINANCE
#include "freight.h"

class finance
{
public:
    finance();
    ~finance();
};

#endif // FINANCE

finance.cpp

#include "finance.h"
using namespace std;

finance::finance()
{
    vector<employee *> vemployee; //first problem line
}

finance::~finance()
{

}

main.cpp

void add_manager()
{
    string name;
    name = get_string_input("Please input the name of the employee.");
    vManagers.push_back(new manager(name)); //second problem line
    ask_employee();
}

Main.cpp also has includes on all my .h files as well as finance.cpp. I am getting errors on both main and finance.cpp saying about expected primary expressions and not declared in scope.

Note:

I'm clearly doing something wrong but I honestly have no idea as vectors is something I haven't been taught yet. If there's a way to do it with arrays I don't mind trying that either.


回答1:


Ok, you need to keep vManagers in class declaration:

//finance.h file
#ifndef FINANCE
#define FINANCE
#include "freight.h" //assuming you have defined manager class here

class finance
{
    public:
        finance();
        ~finance();
        void add_manager();
    private:
        vector<manager*> vManagers;
};

#endif // FINANCE
//finance.cpp file

#include "finance.h"
using namespace std;

finance::finance()
{

}

finance::~finance()
{
    for(int i=0; i< vManagers.size(); i++)
    {
        if(vManagers[i] != NULL)
        {
            delete vManagers[i];
        }
    }
}

finance::add_manager()
{
    string name;
    name = get_string_input("Please input the name of the employee.");
    vManagers.push_back(new manager(name)); //second problem line
    while(ask_employee()
    {
       name = get_string_input("Please input the name of the employee.");
       vManagers.push_back(new manager(name)); //second problem line
    }
}

now you can create and use finance object in main.cpp



来源:https://stackoverflow.com/questions/33316072/vector-array-inside-object-holding-objects-of-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!