c++ - 为什么const对象的成员变量不是const

标签 c++ reference constants c++14 decltype

刚刚问了一个类似的问题,归结为这个问题。

#include <iostream>
using namespace std;

struct A {
    A() : a{1} {};
    int a;
};

template <typename Which>
struct WhichType;

int main() {
    const A a;
    const A& a_ref = a;
    const A* a_ptr = &a;
    WhichType<decltype(a.a)> which_obj; // template evaluates to int
    WhichType<decltype(a_ref.a)> which_ref; // template evaluates to int
    WhichType<decltype(a_ptr->a)> which_ptr; // template evaluates to int

    return 0;
}

为什么模板没有变成 const int 而不是 int

最佳答案

decltype 为您提供操作数的“已声明类型”(当操作数未包含在一组额外的括号中时)。

要获得表达式的实际类型,即 const int,您必须编写 decltype((a.a)) 等等。

decltype 始终为名称以外的左值表达式返回引用类型。

关于c++ - 为什么const对象的成员变量不是const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133079/

相关文章:

c++ - 来自 C++ 资源的对话框的左上角图标

C++ 常量错误

java - 在 Spring xml 配置中使用应用程序常量的最佳方法是什么?

c++ - 如何覆盖常规 malloc,以便在内存泄漏打印输出中打印行号

c++ - 我应该使用哪种类型?

c++ - C++中的十六进制按位运算

c# - 继承基类引用C#

c++ - 引用 STL vector 类型

c++ - 返回成员变量的引用是不好的做法吗?

c - 类型限定符(const)和复杂声明