在C++中也可以使用像C#中的属性。在某些特定的环境我们可以使用这一方法,虽然在效率上会比直接访问要来得慢。但是这点效率基本可以忽略的。。代码大致如下:
我们使用 __declspec( property( get = ???, put = ???) ) ???;来定义某个成员的get和set方法。
我们在调用这个成员的时候,便会自动调用set或get方法,然后将我们的私有成员传递给我们公用的属性成员。
我们也可以根据反汇编看出上面代码的整个调用过程:
main:
push ebp
mov ebp,esp
sub esp,0CCh
push ebx
push esi
push edi
lea edi,[ebp-0CCh]
mov ecx,33h
mov eax,0CCCCCCCCh
rep stos dword ptr [edi]
push 64h
lea ecx,[ts]
call test::set (41C433h) // Set 100
push offset std::endl (41C54Bh)
lea ecx,[ts]
call test::get (41C2A3h) // Get m_nLevel
push eax
mov ecx,offset std::cout (460888h)
call std::basic_ostream<char,std::char_traits<char> >::operator<< (41C686h)
mov ecx,eax
call std::basic_ostream<char,std::char_traits<char> >::operator<< (41CBE0h)
push offset string "pause" (4570C8h)
call @ILT+1945(_system) (41C79Eh)
add esp,4
xor eax,eax
push edx
mov ecx,ebp
push eax
lea edx,ds:[41E62Bh]
call @ILT+1540(@_RTC_CheckStackVars@8) (41C609h)
pop eax
pop edx
pop edi
pop esi
pop ebx
add esp,0CCh
cmp ebp,esp
call @ILT+3570(__RTC_CheckEsp) (41CDF7h)
mov esp,ebp
pop ebp
ret
从红色的字体可以看出,程序自动调用了get和set方法来完成对私有成员的附值和取值。。