如何在C ++中取消对指向对象映射的指针的引用? [英] How to dereference a pointer to a map of pointers to objects in c++?

查看:104
本文介绍了如何在C ++中取消对指向对象映射的指针的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我要使用指针employeePayroll访问类 Employee employeeID : / p>

In the example below, I want to access the employeeID from class Employee by using the pointer employeePayroll:

class Employee { ... int employeeID; ... }
std::map<std::string, Employee *> *_employeePayroll;
std::map<std::string, Employee *> _employeeID;
_employeePayroll = &_employeeID;

如何使用给定密钥访问employeeID,例如

How can I access employeeID with a given key, e.g. to print the content?

推荐答案

... (*_employeePayroll)["Karl"]->employeeID ...

注意:此方法有效,但很危险!一旦 Karl键不存在,它将使程序崩溃。请在下面找到最后一个代码示例。

NOTE: This works, but is dangerous! It will crash the programm as soon as the key "Karl" doesn't exist. Please, find the last code example below.

安全的方法,使用 find iterator

...
itEmployeeID = _employeePayroll->find("Karl");
if ( itEmployeeID != _employeePayroll->end() )
{
    ... (itEmployeeID->second)->employeeID ...

完整的测试代码在这里:

The complete test code is here:

#include    <iostream>
#include    <string>
#include    <map>

class Employee
{
public:
    int     employeeID;

    Employee()
    {
        employeeID = 123;
    }
};

int main(int argc, char* argv[]) {
    std::map<std::string, Employee *>                   *_employeePayroll;
    std::map<std::string, Employee *>                   _employeeID;
    std::map<std::string, Employee *>::const_iterator   itEmployeeID;

    _employeePayroll = &_employeeID;
    (*_employeePayroll)["Karl"] = new Employee;

    itEmployeeID = _employeePayroll->find("Karl");
    if ( itEmployeeID != _employeePayroll->end() )
    {
        std::cout << (itEmployeeID->second)->employeeID;
        std::cout << std::endl;
    }

    return 0;
}

注意:必须清除分配的内存。

NOTE: The allocated memory has to be cleand up.

危险变量的完整测试代码为:

The complete test code of the "dangerous" variant is:

#include    <iostream>
#include    <string>
#include    <map>

class Employee
{
public:
    int     employeeID;

    Employee()
    {
        employeeID = 123;
    }
};

int main(int argc, char* argv[]) {
    std::map<std::string, Employee *> *_employeePayroll;
    std::map<std::string, Employee *> _employeeID;
    _employeePayroll = &_employeeID;

    int iValue;

    (*_employeePayroll)["Karl"] = new Employee;
    iValue = (*_employeePayroll)["Karl"]->employeeID;
    std::cout << iValue;
    std::cout << std::endl;

    return 0;
}

注意:必须清除分配的内存。

NOTE: The allocated memory has to be cleand up.

这篇关于如何在C ++中取消对指向对象映射的指针的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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