在C++中也可以使用像C#中的屬性。在某些特定的環境我們可以使用這一方法,雖然在效率上會比直接存取要來得慢。但是這點效率基本可以忽略的。。代碼大致如下:
#include <iostream><br />using namespace std; </p><p>class test<br />{<br />public:<br /> int get( void )<br /> {<br /> return m_nLevel;<br /> }</p><p> void set( int value )<br /> {<br /> m_nLevel = value;<br /> }</p><p> __declspec( property( get = get, put = set ) ) int level;</p><p>private:<br /> int m_nLevel;<br />};</p><p>int main()<br />{<br /> test ts;<br /> ts.level = 100;<br /> cout << ts.level << endl;<br /> system( "pause" );<br /> return 0;<br />}
我們使用 __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方法來完成對私人成員的附值和取值。。