【问题标题】:const struct { x } vs struct { const x} [duplicate]const struct { x } vs struct { const x} [重复]
【发布时间】:2013-12-20 12:57:16
【问题描述】:

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

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

typedef struct mystruct {
    const int x;
} t1;
const t1 s1;

typedef struct {
    int x;
} t2;
const t2 s2;

? (如果答案是“与类相同”,请为类解释或链接到解释。)

【问题讨论】:

  • -1 甚至没有尝试编译代码。
  • @JesseGood:代码不是完整的语句,当然不会编译。但它可以完成成一个完整的、可编译的语句(参见sftrabbit's answer)。无论如何,修改问题以具有可编译的语句。请考虑删除您的 -1。
  • @einpoklum 该问题已被编辑

标签: c++ struct constants


【解决方案1】:

没有const struct 这样的东西。你可能见过这样的:

const struct {
    int x;
} y;

这是一个结构类型的变量y 的声明。变量yconst,而不是结构。你可以认为它类似于:

struct mystruct {
    int x;
};

const mystruct y;

没有给结构类型命名。

【讨论】:

  • 还有struct {int x;} const y;,我更喜欢第一个。我认为在这种情况下const 适用于对象是相当清楚的。
【解决方案2】:

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

struct A
{
   int x, y;
};

struct B
{
   const int x, y;
};

const A a;   // (plus initialiser)
B b;         // (plus initialiser)

(你当然知道,A其他个实例可能不是const-qualified,然后你就有明显的区别。)

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

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

  2. const-qualifying type(而不是成员)会影响引用绑定:

    void foo(A& a);
    void foo(B& b);
    
    int main()
    {
       const A a;
       B b;
    
       foo(a);  // Error!
       foo(b);  // OK
    }
    

    当然,如果您使用指针而不是引用,情况也是如此。 const 上下文仅在应用于类型而不是封装在成员中时传播到调用代码。

【讨论】:

  • 顺便说一句,谢谢你没有打我。
【解决方案3】:

假设

const struct mystruct1 {
    int x1;
    int x2;
} s1;

struct mystruct2  {
    const int x1;
    int x2;
} s2;

对于s1,您不应为任何成员赋值。

对于s2,不应只为成员x1 赋值。一个是免费的x2


为了更接近您的示例,可以这样做:

typedef const struct mystruct1 {
    int x1;
    int x2;
} S1;

typedef struct mystruct2 {
    const int x1;
    int x2;
} S2;

S1 s1;
S2 s2;

对于s1s2,此处适用与上述相同的规则。


更新

从字面上引用您的问题(暗示通过我的示例进行的更正),就它们所承载的价值的恒定性而言,这两种构造之间没有实际区别。

【讨论】:

  • 在您的示例中,只有一些成员在非 const 结构中是 const 的,而有些则不是,这不是我要问的。当然,这两种结构(请原谅双关语)是不同的。
  • @einpoklum:请看我更新的答案。
  • 嗯,我知道你写了一个很好而详细的答案,但底部是我更新问题的答案,所以你介意留下那部分以便我接受吗? :-)
猜你喜欢
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多