【问题标题】:What is the difference of const and static const? [duplicate]const 和 static const 有什么区别? [复制]
【发布时间】:2014-07-03 03:01:04
【问题描述】:

以下陈述均有效:

static const A = 2;
const B = 3;

声明第一个和第二个有什么区别?

【问题讨论】:

  • 这里已经回答了:stackoverflow.com/questions/3709207/…
  • 可能是您在撰写本文时出现的一些问题回答了您的问题。
  • @yu-hao 不,@guys! 后面的两个骗子都标有c!!实际上存在需要解释的差异;投票重新开放。
  • stackoverflow.com/questions/3709207/… 是一个更合适的骗子。
  • @vin%c3%adcius-gobbo-a-de-oliveira 您应该澄清这些 sn-ps 的范围。

标签: c++


【解决方案1】:

如果static const 被声明在一个类中,它可以从该类和该类的任何实例中访问,所以所有的都将共享相同的值;并且 const 本身对于类的每个实例都是独占的。

给定班级:

class MyClass {
    public:
        static const int A = 2;
        const int B = 4;
};

你可以这样做:

int main() {
    printf("%d", MyClass::A);

    /* Would be the same as */

    MyClass obj;
    printf("%d", obj.A);

    /* And this would be illegal */
    printf("%d", MyClass::B);
}

查看here on Ideone

【讨论】:

  • new 的不必要使用是怎么回事?这也不是您在obj 中访问A 的方式。
  • 对不起,我搞砸了,让我来解决。
  • @Rapptz 抱歉,我将您的评论与静态字段混淆了。
  • 它仍然无法编译。删除不必要和错误的new
  • @LightnessRacesinOrbit 抱歉耽搁了,已经完成了。我也错过了int
【解决方案2】:

静态意味着整个类只共享 1 个常量,其中非静态意味着类的每个实例都单独拥有该常量。

例子:

class A{

static const a;
const b; 
}

//Some other place:

A m;
A n;

对象 m 和 n 具有相同的 a,但不同的 b。

【讨论】:

    猜你喜欢
    • 2012-12-26
    • 2011-04-09
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2013-10-28
    • 2020-11-08
    • 2017-08-16
    相关资源
    最近更新 更多