【问题标题】:How to access methods of classes stored in an unordered_map in C++如何在 C++ 中访问存储在 unordered_map 中的类的方法
【发布时间】:2022-01-01 13:38:01
【问题描述】:

所以我有一个名为 Account 的类,我将它存储在一个 unordered_map 中,但是当我尝试在映射中访问该类的函数时,它无法编译。该类存储在头文件“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;
    }
};

这些函数存储在一个单独的 cpp 文件中,带有 #include "Bank.h"

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.at("Test").getName();'吗?

标签: c++ class unordered-map


【解决方案1】:
accountList["Test"].getName();

无序映射上的[] 运算符(以及std::map)具有必须满足的强制性要求:如果映射的键不存在,则创建它并默认构造相应的值。

很遗憾,您的Account 类没有默认构造函数,因此编译失败。

确实,就在这行代码之前,您将"Test" 的值插入到映射中,所以它会存在。不幸的是,这无关紧要。必须满足operator[] 的所有要求,包括地图的值要求具有默认构造函数。

您有两个选项来解决您的编译错误:

  1. 为您的Account 类添加一个默认构造函数,或者

  2. 您不能使用[],而是使用at();或使用find()(并将其结果与end() 进行比较)。

【讨论】:

  • 我认为除此之外,您还必须为std::string 创建一个哈希函数,对吗?
  • 确实,无序map的key必须有hash函数。好消息是 C++ 库中已经存在一个,无需再做任何事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
相关资源
最近更新 更多