简体   繁体   English

如何访问存储在 C++ 中的 unordered_map 中的类的方法

[英]How to access methods of classes stored in an unordered_map in C++

So I have a class named Account and I am storing it in an unordered_map, but when I try to access the functions of that class within the map, it fails to compile.因此,我有一个名为 Account 的 class 并将其存储在 unordered_map 中,但是当我尝试访问 map 中的 class 的功能时,它无法编译。 The class is stored in a header file "Bank.h" class 存储在 header 文件“Bank.h”中

class Account {
double balance;
std::string username;
public:
Account(double balance, std::string username);

double getBal() {
    return this->balance;
}
std::string getName() {
    return this->username;
}
void updateBal(double amount) {
    this->balance += amount;
}
};

These functions are stored in a separate cpp file with #include "Bank.h"这些函数存储在带有#include "Bank.h" 的单独的 cpp 文件中

std::unordered_map<std::string, Account> accountList;
Account test(100, "Tester");
std::cout << test.getBal();
accountList.insert(std::make_pair("Test", test));
accountList["Test"].getName();
accountList["Test"].getName();

The [] operator on an unordered map (and std::map too) has a mandatory requirement that must be met: if the map's key does not exist, it gets created and the corresponding value gets default-constructed.无序 map(以及std::map也是)上的[]运算符具有必须满足的强制性要求:如果映射的键不存在,则创建它并默认构造相应的值。

Unfortunately, your Account class does not have a default constructor, hence the compilation failure.不幸的是,您的Account class 没有默认构造函数,因此编译失败。

It is true that just before this line of code you are inserting a value for "Test" into the map, so it'll exist.确实,就在这行代码之前,您正在将"Test"的值插入 map,因此它会存在。 This, unfortunately, does not matter.不幸的是,这无关紧要。 All requirements of the operator[] must be met, including the map's value requirement to have a default constructor.必须满足operator[]的所有要求,包括地图的值要求具有默认构造函数。

You have two options to resolve your compilation error:您有两个选项来解决您的编译错误:

  1. Add a default constructor to your Account class, or将默认构造函数添加到您的Account class,或

  2. You cannot use [] , instead use at() ;您不能使用[] ,而是使用at() or use find() (and compare its result to end ()).或使用find() (并将其结果与end () 进行比较)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM