C++ 引用中 & 符号在语义上的准确位置是什么

2023-12-03C/C++开发问题
2

本文介绍了C++ 引用中 & 符号在语义上的准确位置是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

众所周知,声明指针的语义准确方法是

It's pretty common knowledge that the semantically accurate way to declare pointers is

int *x;

代替

int* x;

这是因为 C 将 *x 视为 int,而不是将 x 视为 int 指针.

This is because C sees *x as an int, not x as an int pointer.

这很容易证明

int* a, b;

其中a 是一个int 指针,而b 是一个int.

where a is an int pointer, while b is an int.

在 Stack Overflow 上至少有 5 个重复的问题讨论了这个问题的指针.但是引用呢?

There are at least 5 duplicate questions on Stack Overflow that discuss this issue for pointers. But what about references?

推荐答案

在研究这个问题时,我已经找到了答案:

While researching for this question, I already found the answer:

& 需要像 * 一样编写.

The & needs to be written just like the *.

演示代码类似于指针演示代码:

The demonstration code is similar to the pointer demonstration code:

int main() {
    int a = 0;
    int b = 1;

    int& ar = a, br = b;

    br = 2;

    return b;
}

这返回 1,这意味着 ar 是一个 int 引用,而 br 只是一个整数.

This returns 1, which means that ar is an int reference, while br is just an integer.

这篇关于C++ 引用中 & 符号在语义上的准确位置是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6