类的静态成员变量的使用举例
/** a.cpp 的内容如下:
* 类的静态成员变量.
* 编译链接命令
* g++ -o a.out a1.cpp -std=c++11
*
*/
#include <iostream>
#include <string>
#include <map>
namespace tiao{
class A {
public:
static std::map<std::string, int> map1;
static std::map<std::string, int> map2;
int some_int;
};
};
/**
* 如果注释调下面两行,编译时会报错:
* Undefined symbols for architecture arm64:
"tiao::A::map1", referenced from:
_main in a1-b57425.o
"tiao::A::map2", referenced from:
_main in a1-b57425.o
ld: symbol(s) not found for architecture arm64
*/
std::map<std::string, int> tiao::A::map1;
std::map<std::string, int> tiao::A::map2;
int main(){
tiao::A::map1.insert(std::make_pair(std::string("kshg"), 3));
tiao::A::map2.insert(std::make_pair(std::string("ksh"), 3));
tiao::A A1;
auto it1 = tiao::A::map1.find(std::string("ksh"));
if(it1 == tiao::A::map1.end()) {
std::cout<<"在map1 中没有找到 ksh"<<std::endl;
}
auto it2 = tiao::A::map2.find("ksh");
if(it2 != tiao::A::map2.end()) {
std::cout<<"在map2 中找到 ksh"<<std::endl;
std::cout<<"key: "<< it2->first << "; value: " <<it2->second <<std::endl;
}
return 0;
}