原理背后静态const(非积分)成员初始化语法? [英] Rationale behind static const (non-integral) member initialization syntax?

查看:131
本文介绍了原理背后静态const(非积分)成员初始化语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何初始化一个不是整数的静态成员,但我想知道,这个语法背后的理由是什么?我想能够把值放在类中,就像你可以使用整数成员,a:

I know how to initialize a static member that's not an integer, but I'm wondering, what is the rationale behind the syntax for this? I'd like to be able to just put the value in the class, like you can with an integer member, a la:

class A {
  static const int i = 3;
};

我意识到这可能意味着更多的重建,如果我改变值,因为它是一个更改的标题 - 但在某些情况下,这是不太可能的,只是改变一个#define在标题无论如何。

I realise this could mean more rebuilding if I change the value since it's a change in the header - but in some cases that's pretty unlikely - and just as bad as changing a #define in the header anyway.

这似乎不是一件很难的编译器来理解。有什么技术原因为什么它的工作方式吗?或者,它只是编译器强制执行将实现与定义分离的良好实践的情况?

It doesn't seem like something that would be terribly hard for the compiler to understand. Are there technical reasons why it works the way it does? Or is it just a case of the compiler enforcing the good practice of separating the implementation from the definition?

推荐答案

声明

您需要实际定义某个地方的值。

You need to actually define the value somewhere --- somewhere specific.

因为它是 static 它实际上占用了某处的空间。但是,因为具有该声明的.H文件可以#include在许多源文件中,哪一个定义保存它使用的实际空间?让编译器自动定义每个目标文件中的空间并让链接器将其排序,将违反一个定义规则

Since it is static it's actually taking up space somewhere. But, since the .H file which has that declaration can be #included in many source files, which one defines holds the actual space it is using? Having the compiler automatically define the space in every object file and having the linker sort it out would be a violation of the "One Definition Rule".

这篇关于原理背后静态const(非积分)成员初始化语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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