0

I actually want to make a map of type <int,(class h2)> in class h1 as its private member and then access it from class h2;

here's my code:

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
class h2;
class h1
{
private:
    static map<int, h2> m;
    friend class h2;
};
class h2
{
private:
    string a;

public:
    void fill(string s)
    {
        /*some operations with h1::m*/
        h2 h2_obj;
        h2_obj.a = s;
        (h1::m)[s.size()] = h2_obj;
        return;
    }
    void printMap()
    {
        for (auto i : (h1::m))
        {
            cout << i.first << " : " + i.second.a + "\n";
        }
        return;
    }
};

int main()
{
    while (1)
    {
        string s;
        cout << "Enter:\n";
        getline(cin >> ws, s);
        h2 h2_obj;
        h2_obj.fill(s);
        h2_obj.printMap();
    }
    return 0;
}

but it gives the following compile time error:

undefined reference to `h1::m'
collect2.exe: error: ld returned 1 exit status

By the way, I found another way of doing the task, by using getInstance(); method:

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
class h2;
class h1
{
private:
    map<int, h2> m;
    h1() {}
    friend class h2;

public:
    static h1 &getInstance()
    {
        static h1 obj;
        return obj;
    }
};
class h2
{
private:
    string a;

public:
    void fill(string s)
    {
        /*some operations with h1::m*/
        h2 h2_obj;
        h2_obj.a = s;
        (h1::getInstance().m)[s.size()] = h2_obj;
        return;
    }
    void printMap()
    {
        for (auto i : (h1::getInstance().m))
        {
            cout << i.first << " : " + i.second.a + " " + "\n";
        }
        return;
    }
};

int main()
{
    while (1)
    {
        string s;
        cout << "\nEnter:\n";
        getline(cin >> ws, s);
        h2 h2_obj;
        h2_obj.fill(s);
        h2_obj.printMap();
    }
    return 0;
}

But can someone explain why the linker's showing error while accessing the static map (in the first way), don't we access static fields of a class directly by the class name and scope resolution operator?


Thanks in advance!


user4581301
  • 31,330
  • 6
  • 30
  • 51

0 Answers0