c – 是否可以定义一个指向引用的指针?
发布时间:2020-12-16 03:19:16 所属栏目:百科 来源:网络整理
导读:我正在阅读C Primer,我注意到有一个声明说: Because references are not objects,they don’t have addresses. Hence, we may not define a pointer to a reference. 但是我刚刚写了一个示例代码,并且显示可以创建一个指向引用(d变量)的指针. 代码如下: #i
我正在阅读C Primer,我注意到有一个声明说:
但是我刚刚写了一个示例代码,并且显示可以创建一个指向引用(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: %pn",&a,ptr_to_ref1,ptr_to_ref2); return 0; } 输出: org: 0x7fff083c917c 1: 0x7fff083c917c 2: 0x7fff083c917c 如果你说你能够指出一个参考,那上面的输出应该是不一样的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |