输入/输出参数以及如何在C ++中使用它们 [英] IN/OUT Parameters and how to work with them in C++

查看:242
本文介绍了输入/输出参数以及如何在C ++中使用它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从不同种类的外部库中阅读有关函数的文档时,我总是看到文档状态指出变量必须为[IN/OUT].有人可以让我详细了解[IN/OUT]与通过引用或值传递的函数参数之间的关系.

When reading documentation on functions from external libraries of different kinds I have always seen the documentation state that a variable has to be [IN/OUT]. Could someone give me a detailed understanding on how [IN/OUT] relates to parameters of a function being passed by reference or by value.

这是我遇到的一个函数示例,告诉我它需要一个[IN/OUT]参数:

Here is an example of a function I have come across that tells me it needs an [IN/OUT] parameter:

原型: ULONG GetActivationState(ULONG * pActivationState);

Prototype: ULONG GetActivationState( ULONG * pActivationState );

参数

  • 类型: ULONG *
  • 变量:pActivationState
  • 模式:输入/输出
  • Type: ULONG*
  • Variable: pActivationState
  • Mode: IN/OUT

推荐答案

输入/输出此参数是因为您提供了在函数内部使用的值,函数会对其进行修改以通知您关于函数内部发生的事情.此功能的用法如下:

This parameter is in/out because you provide a value that is used inside the function, and the function modifies it to inform you about something that happened inside the function. The usage of this function would be something like this:

ULONG activationState = 1; // example value
ULONG result = GetActivationState(&activationState);

请注意,您必须提供变量的地址,以便函数可以获取值并在函数外部设置值.例如,GetActivationState函数可以执行以下操作:

note that you have to supply the address of the variable so that the function can get the value and set the value outside the function. For instance, the GetActivationState function can perform something like this:

ULONG GetActivationState(ULONG* pActivationState)
{
    if (*pActivationState == 1)
    {
    // do something
    // and inform by the modification of the variable, say, resetting it to 0
       *pActivationState = 0;
    }
    // ...
    return *pActivationState; // just an example, returns the same value
}

请注意:

  1. 该函数接受参数作为指向UINT的非常量指针.这意味着它可以对其进行修改.
  2. 该函数可以通过取消引用来访问您赋予该参数的值
  3. 该函数可以通过取消引用来再次修改参数.
  4. 调用函数会看到activationState变量,其中包含 new 值(在这种情况下为0).
  1. The function accepts the parameter as a non-const pointer to an UINT. This means it may modify it.
  2. The function can access the value you gave to the parameter by dereferencing it
  3. The function can modify the parameter again by dereferencing it.
  4. The calling function sees the activationState variable holding the new value (0 in this case).

这是通过引用传递"的示例,该示例通过使用C中的指针(以及C ++中的引用)来执行.

This is an example of "pass by reference", which is performed by using pointers in C (and also with references in C++.)

这篇关于输入/输出参数以及如何在C ++中使用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆