如何定义一个指向整数指针的别名? [英] How to define an alias to a pointer to an integer?

查看:50
本文介绍了如何定义一个指向整数指针的别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行以下代码,但出现以下错误.

I am trying to run the following code, but I am getting the following error.

错误:无法声明指向"int&"的指针

error: cannot declare pointer to 'int&'

#include <iostream>
using namespace std;

int main()
{
    int x = 5;
    int *ptr = &x;

    int &(*y) = ptr;
    *y = 5;

    cout << *ptr << endl;
    return 0;
}

推荐答案

如果只需要一个指向相同内存区域的新指针,请使用:

If you just want a new pointer to the same region of memory, use:

int *y = ptr;

这并不是别名",因为如果您更改 * ptr * y ,两者都会更改,但是如果您自己更改指针,则另一个将不会更新.

This not so much an "alias" in that if you change *ptr or *y, both will change, but if you change the pointers themselves, the other will not be updated.

如果您确实希望引用一个指针,请使用:

If you actually do want a reference to a pointer, use:

int *&y = ptr;

这篇关于如何定义一个指向整数指针的别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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