在结构/类中使用静态const int [英] using a static const int in a struct/class

查看:90
本文介绍了在结构/类中使用静态const int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct A {
    static const int a = 5;

    struct B {
       static const int b = a;
    };

 };

 int main() {
   return A::B::b;
 }

上面的代码编译。但是,如果你去的有效的C ++书由斯科特·迈尔斯(第14页);
除了声明之外,我们还需要一个定义。
任何人都可以解释为什么这是一个异常?

The above code compiles. However if you go by Effective C++ book by Scott Myers(pg 14); We need a definition for a in addition to the declaration. Can anyone explain why this is an exception?

推荐答案

C ++编译器允许静态const整数在其声明的位置指定其值。这是因为变量基本上不需要,并且只存在于代码中(它通常是编译出来的)。

C++ compilers allow static const integers (and integers only) to have their value specified at the location they are declared. This is because the variable is essentially not needed, and lives only in the code (it is typically compiled out).

其他变量类型(如static const char *)通常不能在声明的位置定义,需要单独定义。

Other variable types (such as static const char*) cannot typically be defined where they are declared, and require a separate definition.

对于一点点更多的解释,意识到访问全局变量通常需要在低级代码中进行地址引用。但是你的全局变量是一个整数,它的大小通常是地址的大小,编译器意识到它永远不会改变,所以为什么要添加指针抽象?

For a tiny bit more explanation, realize that accessing a global variable typically requires making an address reference in the lower-level code. But your global variable is an integer whose size is this typically around the size of an address, and the compiler realizes it will never change, so why bother adding the pointer abstraction?

这篇关于在结构/类中使用静态const int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆