在C++中也可以使用像C#中的属性。在某些特定的环境我们可以使用这一方法,虽然在效率上会比直接访问要来得慢。但是这点效率基本可以忽略的。。代码大致如下:
#include <iostream> using namespace std; class test { public: int get( void ) { return m_nLevel; } void set( int value ) { m_nLevel = value; } __declspec( property( get = get, put = set ) ) int level; private: int m_nLevel; }; int main() { test ts; ts.level = 100; cout << ts.level << endl; system( "pause" ); return 0; }
我们使用 __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方法来完成对私有成员的附值和取值。。
本文介绍如何在C++中实现类似C#的属性功能,通过__declspec(property)来定义成员的get和set方法,并展示了完整的代码实例及反汇编调用过程。
1220

被折叠的 条评论
为什么被折叠?



