C++ 编译错误:const int*&;reference=指向int的指针。为什么?
我试图将C++ 编译错误:const int*&;reference=指向int的指针。为什么?,c++,pointers,reference,C++,Pointers,Reference,我试图将int*类型的参数传递给constint*&类型的函数参数,以避免可能的值更改。正如我在问题中所说,它不起作用。 我假设参考考虑了int*和const int*两种不兼容的类型,但我想知道为什么 我尝试将引用设置为const int*const&,虽然它不是我所需要的,但它仍然有效。 我正在编写的代码是一个简单的函数,可以将两个指针交换到int void swap(const int *&item1, const int *&item2) { const int *tem
int*
类型的参数传递给constint*&
类型的函数参数,以避免可能的值更改。正如我在问题中所说,它不起作用。
我假设参考考虑了int*
和const int*
两种不兼容的类型,但我想知道为什么
我尝试将引用设置为const int*const&
,虽然它不是我所需要的,但它仍然有效。
我正在编写的代码是一个简单的函数,可以将两个指针交换到int
void swap(const int *&item1, const int *&item2)
{
const int *temp = item1;
item1 = item2;
item2 = temp;
}
据我所知(如果我错了,请纠正我),使用不兼容(但可转换)类型的对象初始化的对const的引用应生成兼容类型的临时对象,使用转换的不兼容对象初始化它,并最终将引用绑定到该对象。
例如
int number = 10; const double &ref = number;
应等同于:
int number = 10; const double temp = number; const double &ref = temp;
在这种情况下,
&ref!=&数字
但当我尝试时,int*ptr=nullptr;常数int*常数&ref=ptr代码>&ptr
和&ref
是相同的。int*
和const int*
不兼容。int*
类型的值隐式转换为const int*
类型的值,但不能将int*
变量当作const int*
变量使用(不能存储const int
的地址,这是实const int*
所允许的)您不能像使用int*
变量那样使用const int*
(您不能写入目标,这是真正的int*
所允许的)。这不是对const的引用。不,绑定到左值不会创建引用。double&ref=number代码>使其引用编号
<代码>双参考=温度代码>使其引用不同的变量,而不是引用编号。它们根本不相等。可能重复@chris:No,int number;double&ref=数字代码>是编译错误,除了VisualC++中,在扩展中,他创建了一个临时的描述。代码>整数;const double&ref=编号代码>是合法C++,并创建临时的。抱歉…我写错了