微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 是否可以定义一个指向引用的指针?

我正在阅读C Primer,我注意到有一个声明说:

Because references are not objects,they don’t have addresses. Hence,
we may not define a pointer to a reference.

但是我刚刚写了一个示例代码,并且显示可以创建一个指向引用(d变量)的指针.

代码如下:

#include <iostream>
using namespace std;

int main(){
   int a = 1024;

   int &b = a; // a reference to int
   int &c = b; // a reference to another reference
   int *d = &b; // a pointer to a reference
   int *(&e) = d; // a reference to a pointer 

   a = 100;
   cout << b << endl;
   cout << c << endl;
   cout << *d << endl;
   cout << *e << endl;
}

那么,我的测试有什么问题吗?或者C Primer中的声明是错误的?

我正在读C Primerfifth版.声明在第52页,2.3.2.

解决方法

报价是正确的,因为您指针指向原始对象,而不是其引用.下面的代码显示了这个事实:
#include <stdio.h>
#include <stdlib.h>

int main() {
  int a = 0;
  // two references referring to same object
  int& ref1_a = a;
  int& ref2_a = a;
  // creating a different pointer for each reference
  int* ptr_to_ref1 = &ref1_a;
  int* ptr_to_ref2 = &ref2_a;

  printf("org: %p 1: %p 2: %p\n",&a,ptr_to_ref1,ptr_to_ref2);

  return 0;
}

输出

org: 0x7fff083c917c 1: 0x7fff083c917c 2: 0x7fff083c917c

如果你说你能够指出一个参考,那上面的输出应该是不一样的.

原文地址:https://www.jb51.cc/c/111851.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐