在C ++中使用指针调用函数 [英] Calling a function using pointers in C++

查看:156
本文介绍了在C ++中使用指针调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简单,我正在学习C ++,并且可以使用指针.我了解基本概念,但遇到了一些麻烦. 调用该函数的语法是什么?

Pretty straightforward, I'm relearning C++ and I'm up to pointers. I understand the basic concept, but I'm having a little trouble. What would the syntax for calling this function be?

void getTime(int& hours, int& minutes, int& seconds) const
{
    hours = hr;
    minutes = min;
    seconds = sec;
}

您可能已经猜到了,函数的要点是将以小时,分钟和秒为单位的时间返回到位于函数调用所在范围内的三个指针.假定hr,min和sec已经定义.

The point of the function, as you've probably guessed, is to return the time in hours, minutes and seconds to three pointers in located in whatever scope the function call is in. Assume that hr, min, and sec have already been defined.

此外,如果有人想详细说明指针(特别是何时使用&和何时使用*),那将不胜感激.预先感谢.

Also, if anyone would like to elaborate on the pointers a little (particularly when to use & and when to use *) that would be greatly appreciated. Thank in advance.

推荐答案

您的函数签名使用&,它表示传递引用.这意味着您只需以

Your function signature uses &, which denotes a pass-by-reference. This means that you simply invoke your function as

int h, m, s;

// ... code ...

getTime(h, m, s);

由于您的函数通过引用传递了这些参数,因此,每当getTime()更改传递的参数之一时,更改将传播到函数外部,而不是通过值传递的参数将更改限制在函数范围之内.

Because your function passes these arguments by reference, whenever getTime() changes one of the arguments passed, the changes propagate to outside the function, as opposed to arguments passed by value where changes are limited to the function scope.

您可以通过将指针传递给变量来达到类似的效果:

You can achieve a similar effect by passing pointers to variables instead:

void getTime(int * hours, int * minutes, int * seconds)
{
     // do stuff
}

// ... code ...

int h, m, s;
getTime(&h, &m, &s);

在后一种情况下,&地址运算符.通过取消引用传递的地址,您的函数可以在其函数范围之外对内存进行更改.

In the latter context, the & is the address-of operator. By dereferencing the addresses passed, your function can make changes to memory outside its function scope.

这篇关于在C ++中使用指针调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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