0

I am new to C++ and got confused when using static methods.. This file defined a class A-----classa.h

#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
class A{
    public:
        static void func1();
        static void func2();
    private:
        static std::map<int, std::string> testmap;
};

I hope the other functions in this class can share the same map----classa.cpp

#include <iostream>
#include <stdio.h>
#include <vector>
#include "classa.h"

void A::func1(){
    std::cout<<"func1#####"<<std::endl;
    A::testmap.insert(std::make_pair(1, "func1"));
    std::cout<< testmap[1] << std::endl;
}
void A::func2(){
    std::cout<<"func2#####"<<std::endl;
    A::testmap.insert(std::make_pair(2, "func2"));
    std::cout<< testmap[2] << std::endl;
}
int main(){ 
    A::func1();
    A::func2();
}

But it does not work and got this err:

Undefined symbols for architecture x86_64:
  "A::testmap", referenced from:
      A::func1() in classa-0798d3.o
      A::func2() in classa-0798d3.o
ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'd appreciate it if I could get some help. Thanks!

1 Answers1

0
testmap  is needs to be initialized before use.

You can read more here

Here is the solution to your problem:

#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
using namespace std;
class A{
   public:
      static void func1();
      static void func2();
   private:
      static std::map<int, std::string> testmap;
};

 std::map<int, std::string> A::testmap{
   []{
       map<int, std::string> v;

       v.insert(std::make_pair(1, "func1"));
       v.insert(std::make_pair(2, "func2"));

     return v;
  }() // Call the lambda right away
};

void A::func1(){
    std::cout<<"func1#####"<<std::endl;
    std::cout<< A::testmap[1] << std::endl;
}
void A::func2(){
   std::cout<<"func2#####"<<std::endl;
   std::cout<< A::testmap[2] << std::endl;
}
int main(){
  A::func1();
  A::func2();
  return 0;
}

output:

Nsikan Sylvester
  • 583
  • 5
  • 14