首页 > 解决方案 > C ++中引用变量和常规变量之间的区别?

问题描述

在 C++ 中定义引用后,引用和普通变量之间有什么区别吗?

例如,在我在下面的代码中定义了一个引用之后: int x = 10; int& xRef = x;

有没有办法告诉 xRef 是对 int 的引用,而不仅仅是一个普通的 int?int& 是它自己的类型吗?

标签: c++reference

解决方案


有没有办法告诉 xRef 是对 int 的引用,而不仅仅是一个普通的 int?

您可以使用std::is_reference

#include <iostream>
#include <type_traits>

int main ()
{
    int i = 0;
    int& ri = i;
    
    if (std::is_reference <decltype (i)>::value)
        std::cout << "i is a reference\n";

    if (std::is_reference <decltype (ri)>::value)
        std::cout << "ri is a reference\n";
}    

输出:ri is a reference

所以,

int& 是它自己的类型吗?

是的。


推荐阅读