如何在C ++中取消对指向对象映射的指针的引用? [英] How to dereference a pointer to a map of pointers to objects in 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屋!