const struct {x} vs struct {const x}

ein*_*ica -7 c++ struct const constants

这是一个相当简单的问题,但不知何故很难找到一个简单的答案.

在C++中,(编辑)const修改的结构变量和(编辑:)非const结构变量之间的区别是什么,但结构具有所有const成员?:

typedef struct mystruct {
    const int x;
} t1;
const t1 s1;
Run Code Online (Sandbox Code Playgroud)

VS

typedef struct {
    int x;
} t2;
const t2 s2;
Run Code Online (Sandbox Code Playgroud)

?(如果答案是"与课程相同",那么请为课程解释或链接到解释.)

Jos*_*eld 6

没有这样的事情const struct.您可能已经看到过这样的事情:

const struct {
    int x;
} y;
Run Code Online (Sandbox Code Playgroud)

这是y带有struct类型的变量的声明.变量yconst,不是结构.您可以将其视为类似于:

struct mystruct {
    int x;
};

const mystruct y;
Run Code Online (Sandbox Code Playgroud)

不给结构类型命名.

  • 还有`struct {int x;} const y;`,我比第一个更喜欢它.我认为在这种情况下`const`适用于对象是相当清楚的. (3认同)

Lig*_*ica 5

这两个对象和以下对象之间实际上几乎没有区别:ab

struct A
{
   int x, y;
};

struct B
{
   const int x, y;
};

const A a;   // (plus initialiser)
B b;         // (plus initialiser)
Run Code Online (Sandbox Code Playgroud)

(当然,您知道 的其他实例A可能不符合条件const,然后您就有明显的区别。)

在一种情况下,您不能以与另一种情况不同的方式访问成员。但:

  1. 在这两种情况下,您必须确保初始化成员(我在这里没有这样做);

  2. const-限定类型(而不是成员)会影响引用绑定:

    void foo(A& a);
    void foo(B& b);
    
    int main()
    {
       const A a;
       B b;
    
       foo(a);  // Error!
       foo(b);  // OK
    }
    
    Run Code Online (Sandbox Code Playgroud)

    当然,如果您使用指针而不是引用,也是如此。该const上下文仅扩散到当它应用到调用代码类型,而不是内的成员封装。