C ++静态成员变量及其初始化 [英] C++ static member variable and its initialization

查看:127
本文介绍了C ++静态成员变量及其初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



对于C ++类中的静态成员变量 - 初始化在类外完成。我想知道为什么?这是什么逻辑推理/约束?还是纯粹的传统实现 - 标准不想纠正?


For static member variables in C++ class - the initialization is done outside the class. I wonder why? Any logical reasoning/constraint for this? Or is it purely legacy implementation - which the standard does not want to correct?

我认为在类中初始化是更直观,更少的混乱。它还给出了变量的静态和全局的意义。例如,如果你看到静态const成员。

I think having initialization in the class is more "intuitive" and less confusing.It also gives the sense of both static and global-ness of the variable. For example if you see the static const member.

推荐答案

基本上,这是因为静态成员必须在一个翻译单元,以便不违反一种定义规则。如果语言允许类似:

Fundamentally this is because static members must be defined in exactly one translation unit, in order to not violate the One-Definition Rule. If the language were to allow something like:

struct Gizmo
{
  static string name = "Foo";
};

那么 name #include 这个头文件

C ++允许你定义 >静态成员在声明中,但你仍然必须在单个翻译单元中包括一个定义,但这只是一个快捷方式,或语法糖。所以,这是允许的:

C++ does allow you to define integral static members within the declaration, but you still have to include a definition within a single translation unit, but this is just a shortcut, or syntactic sugar. So, this is allowed:

struct Gizmo
{
  static const int count = 42;
};

只要a)表达式 const 整数或枚举类型,b)可以在编译时评估表达式,以及c)在某处没有违反一个定义规则的定义:

So long as a) the expression is const integral or enumeration type, b) the expression can be evaluated at compile-time, and c) there is still a definition somewhere that doesn't violate the one definition rule:

file:gizmo.cpp

file: gizmo.cpp

#include "gizmo.h"

const int Gizmo::count;

这篇关于C ++静态成员变量及其初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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