对象内的向量/数组,包含另一个类的对象 [英] Vector/Array inside Object, Holding Objects of Another Class

查看:108
本文介绍了对象内的向量/数组,包含另一个类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试存储基类的对象( employee ),或存储指向另一个类的向量/数组内的对象的指针( finance )对象。员工对象的数量取决于用户,因此它需要动态工作。到目前为止,我有这个:

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

财务。 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 我的所有 .h 文件以及 finance.cpp 上也都包含了。我在main和 finance.cpp 上都遇到了错误,说预期的主表达式而不是在范围内声明。

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.

我显然做错了事,但老实说我不知道​​,因为向量还没被教过。如果有办法用数组来做,我也不介意尝试。

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.

推荐答案

好,您需要保持 vManagers 在类声明中:

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
    }
}

现在您可以在main.cpp中创建和使用财务对象

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

这篇关于对象内的向量/数组,包含另一个类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆