【发布时间】:2019-01-31 20:22:01
【问题描述】:
我有一个简单的问题:据我所知,我可以声明指向某个数据类型的 const 指针或指向常量数据类型的指针,但我只能声明对常量数据类型的引用,而不能声明对数据类型的常量引用;引用已经是常量,因为它不能重新绑定到另一个对象。
因此,当我尝试创建 const ref to someDataType 时,会出现编译时错误。但重要的是当与type alias 一起使用时,使用typedef 或using。例如:
#include <iostream>
int main() {
int i{ 10 };
// int& const r1{ i }; // error: ‘const’ qualifiers cannot be applied to ‘int&’. Ok here.
using rInt = int&; // or typedef int& rInt;
const rInt r2{ i }; // why const is allowed here?
++r2; // this proves that the const is applied to the reference not to the object referred to.
std::cout << r2 << std::endl; // 11
}
正如您在上面看到的,我可以将const 添加到我认为在该上下文中是冗余的引用中。但是为什么 C++ 允许使用类型别名而不是直接使用呢?
【问题讨论】:
-
在我的编译器上,我得到了
Alex24.cpp:8:5: warning: 'const' qualifier on reference type 'rInt' (aka 'int &') has no effect [-Wignored-qualifiers]...您是否打开了警告?我认为这与您的问题无关,因为您在问为什么允许 const (即使被忽略)。 -
@FrançoisAndrieux 那为什么我可以通过
rInt更改对象呢? -
和
using t_Value = int const; t_Value const value{};一样,第二次申请const没有效果。但是,您的引用是对可变对象的引用,因此您可以使用该引用更改对象。请注意,将const添加到rInt不会将引用转换为对 const 限定对象的引用。 -
@Alex24 “但是为什么 C++ 允许使用类型别名而不是直接使用呢?” 我不相信该语言正式禁止它。编辑:对于它的价值
r1在 VC++ 14.0 中产生警告。 -
您可能想要添加
language-lawyer标签,因为我假设您想要标准中的章节+诗句。