1

Compiler says
ERROR1: the object has type qualifiers that are not compatible with the member function "NAME::getName" object type is : const NAME

ERROR2: 'std::string NAME::getName(void)': cannot convert 'this' pointer from '_Ty1' to 'NAME &'

on cout << (it->first).getName();

So why is that and how to make it work?

#include <map>
#include <iostream>
using namespace std;

class NAME
{
private:
    string name;

public:
    NAME(string name)
    {
        this->name = name;
    }

    string getName()
    {
        return name;
    }
};

int main()
{
    map <NAME, int> telephoneBook = { {NAME("Alex"), 1122},
                                      {NAME("Oleg"), 3344} };

    for (auto it = telephoneBook.begin(); it != telephoneBook.end(); ++it)///вывод на экран
    {
        cout << (it->first).getName(); // error 1 and error2
    }
}
Denys_newbie
  • 1,140
  • 5
  • 15
  • Your `getName()` function [should be `const`](https://isocpp.org/wiki/faq/const-correctness#const-member-fns) because `map`'s keys are constants once inserted. Also, in the future please insert full error messages without omitting any information instead of "marking" corresponding lines and truncating messages. – yeputons Nov 23 '20 at 15:41
  • `getName` is not declared `const`, which seems to be some of the problem. Also, sounds like you are not really using the right data structure or at least not the right kind of key and value. – crashmstr Nov 23 '20 at 15:41
  • @Sam I guess it should be an error as well, but that's not what OP is asking about. – Yksisarvinen Nov 23 '20 at 15:44
  • 1
    The compiler should've also spewed out a bunch of errors, due to a lack of a meaningful `<` operator for the custom class, way before it got to these errors. – Sam Varshavchik Nov 23 '20 at 15:44
  • I don't truncated any errors, compiler gived me only two errors – Denys_newbie Nov 23 '20 at 15:53

0 Answers0