Skip to content

Commit

Permalink
[faq] 简化对引用与值类别的解释
Browse files Browse the repository at this point in the history
  • Loading branch information
FeignClaims committed Feb 1, 2024
1 parent 5c3b049 commit 6a1d341
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions docs/faq/basic_concepts/cross/reference-value_category.irst
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
:cpp:`T&` 只能引用左值即 "已经存在的对象", 因此不进行会产生临时对象的隐式类型转换.

.. code-block:: cpp
:linenos:
.. tabs::

.. tab:: 引用已经存在的对象

.. code-block:: cpp
:linenos:

int value = 0;
int& reference = value;

.. tab:: 不能引用临时对象

.. code-block:: cpp
:linenos:

double value = 0;
int& reference = value; // 错误: double 隐式类型转换为 int 是产生新的临时对象

int value1 = 0;
int& reference1 = value1;
.. tab:: 基类引用派生类

double value2 = 0;
int& reference2 = value2; // 错误: double 隐式类型转换为 int 是产生新的临时对象
int& reference3 = reinterpret_cast<int&>(value2); // 语法上正确: 产生的是引用
.. code-block:: cpp
:linenos:

class A {};
class B : public A {};
B b;
A& = b; // 正确: 基类引用兼容于 (reference-compatible to) 公用继承自它的类
class A {};
class B : public A {};
B b;
A& = b; // 正确: 基类引用兼容派生类

:cpp:`T const&` 既能引用左值又能引用右值: 既然能引用临时值, 则会在引用时发生隐式类型转换.
:cpp:`T const&` 既能引用左值又能引用右值: 既然能引用右值即临时值, 则会在引用时发生隐式类型转换.

.. code-block:: cpp
:linenos:
Expand Down

0 comments on commit 6a1d341

Please sign in to comment.