c++类静态成员特点:
1、在类中申明,在类外别处定义
2、该类所有实例,都共享类外定义存储单元
3、类实例不会为它分配空间去引用类外定义的存储单元
4、在访问类静态成员时,是采用指令指针在偏移方式实现的
如下源码含有静态成员a,
#include <iostream>
using namespace std;class shared
{
static int a;
int b;
public:
void set(int i, int j)
{
a=i;
b=j;
}
void show();
} ;
int shared::a; // define a
void shared::show()
{
cout << "This is static a: " << a;
cout << "\nThis is non-static b: " << b;
cout << "\n";
}
int main()
{
shared x, y;
x.set(1, 1); // set a to 1
x.show();
y.set(2, 2); // change a to 2
y.show();
x.show(); /* Here, a has been changed for both x and y because a is shared by both objects. */
return 0;
}
(gdb) p sizeof(shared)
$5 = 4
(gdb)
(gdb)
(gdb)
(gdb)
(gdb) p &shared::a
$6 = (int *) 0x601174 <shared::a>
(gdb)
(gdb)
(gdb)
(gdb)
(gdb) disassemble /m shared::set
Dump of assembler code for function shared::set(int, int):
11 void set(int i, int j)
0x00000000004008f2 <+0>: push rbp
0x00000000004008f3 <+1>: mov rbp,rsp
0x00000000004008f6 <+4>: mov QWORD PTR [rbp-0x8],rdi
0x00000000004008fa <+8>: mov DWORD PTR [rbp-0xc],esi
0x00000000004008fd <+11>: mov DWORD PTR [rbp-0x10],edx
12 {
13 a=i;
0x0000000000400900 <+14>: mov eax,DWORD PTR [rbp-0xc]
0x0000000000400903 <+17>: mov DWORD PTR [rip+0x20086b],eax # 0x601174 <_ZN6shared1aE>
14 b=j;
0x0000000000400909 <+23>: mov rax,QWORD PTR [rbp-0x8]
0x000000000040090d <+27>: mov edx,DWORD PTR [rbp-0x10]
0x0000000000400910 <+30>: mov DWORD PTR [rax],edx
15 }
0x0000000000400912 <+32>: pop rbp
0x0000000000400913 <+33>: ret
End of assembler dump.