C 中使用屬性 property

2021-08-23 13:40:03 字數 1560 閱讀 5332

在c++中也可以使用像c#中的屬性。在某些特定的環境我們可以使用這一方法,雖然在效率上會比直接訪問要來得慢。但是這點效率基本可以忽略的。。**大致如下:

#include using namespace std; class test void set( int value ) __declspec( property( get = get, put = set ) ) int level; private: int m_nlevel; }; int main()

我們使用 __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>::operator<< (41c686h)

mov ecx,eax

call std::basic_ostream>::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 中使用屬性 property

在c 中也可以使用像c 中的屬性。在某些特定的環境我們可以使用這一方法,雖然在效率上會比直接訪問要來得慢。但是這點效率基本可以忽略的。大致如下 我們使用 declspec property get put 來定義某個成員的get和set方法。我們在呼叫這個成員的時候,便會自動呼叫set或get方法,...

qss中使用自定義屬性 property

q property type name read getfunction write setfunction reset resetfunction notify notifysignal designable bool scriptable bool stored bool user bool ...

C 中使用屬性

使用屬性,避免將資料成員直接暴露給外界 item always use properties instead of accessible data members.學習研究.net的早期,經常碰到一些學習c net的朋友問,要屬性這種華而不實的東西做什麼?後來做專案時也時常接到team裡的人的抱怨反...