运行时 staticintgetv() { 0x400816 push %rbp 0x400817 mov %rsp,%rbp 0x40081a sub $0x10,%rsp int a=5; a++; cout<<a<<endl; return4; }
staticint global1=4; intmain() { staticint locstatic1=5; int loc1=global1; int loc2=locstatic1; // cout<<getv()<<endl; getv(); 0x400866 callq 0x400816 <getv()>
static和类相关
static成员变量的使用
static成员变量是类的所有对象共有的,但是只有一份,通过类也可以访问到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSomething { public: staticint s_value; // declares the static member variable }; int Something::s_value = 1; // defines the static member variable (we'll discuss this section below) intmain() { // note: we're not instantiating any objects of type Something Something::s_value = 2; std::cout << Something::s_value << '\n'; return0; }
1 2 3 4 5 6 7 8 9 10 11 12 13
_ZN9Something7s_valueE: .long1 .text .globl main .type main, @function
classIDGenerator { private: staticint s_nextID; // Here's the declaration for a static member public: staticintgetNextID(); // Here's the declaration for a static function }; // Here's the definition of the static member outside the class. Note we don't use the static keyword here. // We'll start generating IDs at 1 int IDGenerator::s_nextID = 1; // Here's the definition of the static function outside of the class. Note we don't use the static keyword here. intIDGenerator::getNextID(){ return s_nextID++; } intmain() { for (int count=0; count < 5; ++count) std::cout << "The next ID is: " << IDGenerator::getNextID() << '\n'; return0; }