IN/OUT 参数以及如何在 C++ 中使用它们

IN/OUT Parameters and how to work with them in C++(IN/OUT 参数以及如何在 C++ 中使用它们)

本文介绍了IN/OUT 参数以及如何在 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++.)

这篇关于IN/OUT 参数以及如何在 C++ 中使用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:IN/OUT 参数以及如何在 C++ 中使用它们

基础教程推荐