MFC中GetDlgItemInt()方法的疑惑与使用总结

来源:互联网 发布:淘宝网店推广毕业论文 编辑:程序博客网 时间:2024/06/05 18:30

MSDN中是这样描述CWnd::GetDlgItemInt方法的:

UINT GetDlgItemInt(    int nID,    BOOL* lpTrans = NULL,    BOOL bSigned = TRUE  ) const;

Parameters
--------------------------------------------------------------------------------


nID 
Specifies the integer identifier of the dialog-box control to be translated.


lpTrans 
Points to the Boolean variable that is to receive the translated flag.


bSigned 
Specifies whether the value to be retrieved is signed.


Return Value
--------------------------------------------------------------------------------


Specifies the translated value of the dialog-box item text. Since 0 is a valid return value, lpTrans must be used to detect errors.If a signed return value is desired, cast it as an int type.


The function returns 0 if the translated number is greater than INT_MAX (for signed numbers) or UINT_MAX (for unsigned).


When errors occur, such as encountering nonnumeric characters and exceeding the above maximum, GetDlgItemInt copies 0 to the location pointed to by lpTrans. If there are no errors, lpTrans receives a nonzero value. If lpTrans is NULL, GetDlgItemInt does not warn about errors.


Remarks
--------------------------------------------------------------------------------


It translates the text of the specified control in the given dialog box into an integer value by stripping any extra spaces at the beginning of the text and converting decimal digits. It stops the translation when it reaches the end of the text or encounters any nonnumeric character.


If bSigned is TRUE, GetDlgItemInt checks for a minus sign (–) at the beginning of the text and translates the text into a signed number. Otherwise, it creates an unsigned value.


It sends a WM_GETTEXT message to the control.

显然该方法可以将文本控件中的文本直接转换为数字。看到Return Value的第一句,知道函数的返回值就是转换出来的数据。但是数据类型竟然只有UINT,而函数参数列表中明显声明了用bSigned参数区分返回值是有符号数还是无符号数。这岂不是与返回值为UINT矛盾了?

这时候看到Return Value中的第三句话:If a signed return value is desired, cast it as an int type.(如果需要返回的值是有符号数,那么直接将返回值看做int类型即可。) 于是一切便明朗了,因为一个数是否有符号仅仅在内存中是看不出来的,所以MS在描述此函数原型的时候似乎偷了个懒,无论返回值是否有符号,一律按照无符号数来返回。至于这个数是否有符号则需要程序员来进行一次转换。直接上代码:

int i = GetDlgItemInt(IDC_EDIT_TEMPERATURE, NULL, 1);  //若看做有符号数,则bSigned为1,返回值直接以int类型去接收UINT j = GetDlgItemInt(IDC_EDIT_TEMPERATURE, NULL, 0);  //若看做无符号数,则bSigned为0,返回值按照UINT类型来接收


0 0
原创粉丝点击