c++ - 解压 C++ 指针/引用语法

标签 c++ arrays function pointers reference

最近我进行了一次知识检查,其中包含的代码一直让我感到困惑。在这里:

#include <iostream>
using namespace std;

int f1(int *a) {
    return *a + 1;
}

int *f2(int *a) {
    return a + 1;
}

int *f3(int &a) {
    return &a + 1;
}

int main() {
    int t[] = {0, 1, 2, 3};
    cout << f1(f3(*f2(t)));
    return 0;
}

评估的问题是“程序的输出是什么?”。通过编译这个我得到三个。

我知道这显示了处理指针和引用的不同方式,但我无法理解逻辑。

有人可以评论此代码的不同行,分解处理对 t 数组/vector 的引用的方法吗?特别是我不明白 int *function 是如何与结果交互的(它是返回一个引用还是一个我无法分辨的值)。然后在函数的不同主体内部如何使用或不使用取消引用/引用运算符。我只是想弄清楚这一切的逻辑,但我一直在绕轴转。

编辑 在一些帮助下,我相信我已经舔过了这个。在下面检查我的答案。

最佳答案

分而治之:

int t[] = {0, 1, 2, 3}; // t is a pointer to the first element of the array
int &a(*f2(t)); // f2(t) returns a pointer, so you need to "dereferencing" using *, to get the referece to the value
int *b = f3(a); //f3(a) take an int by reference and return a pointer to an int
cout << f1(b); //f1(b) take a pointer to an int and returns an int value;

还要注意这两行:

return &a + 1;

return *a + 1;

也许他们并没有按照您的想法去做。

请记住,这 3 个函数只是通过指针算法递增指针

关于c++ - 解压 C++ 指针/引用语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42820231/

相关文章:

python - gcc 应该在不传递 -I/usr/include/python2.7/的情况下找到 Python.h 吗?

c++ - C++ 类中的枚举

javascript - 如何将对象数组拆分为 block

arrays - 获取 Golang 标志作为字节数组

c++ - 从另一个构造函数的主体调用构造函数

c++ - 查找二进制到 C/C++ 的链接

c++ - 如何在包含 10 个元素的字符串数组中查找字符串

function - 为什么 Matlab 看不到我的函数?

Xcode 无法检查 who to blame 信息

bash - 退出函数栈而不退出 shell