简体   繁体   中英

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. The class is stored in a header file "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"

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.

Unfortunately, your Account class does not have a default constructor, hence the compilation failure.

It is true that just before this line of code you are inserting a value for "Test" into the map, so it'll exist. This, unfortunately, does not matter. All requirements of the operator[] must be met, including the map's value requirement to have a default constructor.

You have two options to resolve your compilation error:

  1. Add a default constructor to your Account class, or

  2. You cannot use [] , instead use at() ; or use find() (and compare its result to end ()).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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