为什么非const,非int / enum静态数据成员必须在定义之外初始化? [英] Why do non-const, non-int/enum static data members have to be initialized outside the definition?

查看:116
本文介绍了为什么非const,非int / enum静态数据成员必须在定义之外初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,只有static,const和int / enum(pre c ++ 11)的数据成员可以在类声明中初始化。 所有其他静态数据成员都必须在全局命名空间范围内定义(即在类定义的主体之外),并且只能在这些定义中初始化。



为什么可以其他静态数据成员是否在类定义中初始化?是否有一个特定的原因被禁止?



如果数据成员是特定于类的,为什么它们在全局命名空间范围内声明,而不是某些与它们相关的范围class?

解决方案


为什么其他静态数据成员不能在类定义中初始化?是否有一个特定的原因被禁止?


很可能是因为C ++有单独的翻译单元。编译器需要选择一个将放置这些符号的初始化逻辑的对象文件。如果数据成员是特定于该类的,那么为什么要这样做呢?如果数据成员是特定于该类的,那么为什么它们是在全局命名空间范围内声明的,而不是与它们的类相关的某个范围?

因为这就是C ++的类成员。这与成员函数等其他类成员没有区别:

头文件:

  namespace示例{

//头中声明的类
struct some_class
{
//成员变量
static float示例;
//成员函数
void DoStuff()const;
};

$ b

源文件:

 命名空间示例{

//实现成员变量
float some_class :: example = 3.14159;
//实现成员函数
void some_class :: DoStuff()const
{
// ....
}
}

允许静态const成员在头文件中被初始化是一个特殊的例外,因为它允许编译器将它们当作编译时常量。也就是说,您可以使用它们在类定义中定义数组或其他类似位的大小。


I understand that only data members which are static, const and int/enum (pre c++11) can be initialized inside the class declaration. "All other static data members must be defined at global namespace scope (i.e. outside the body of the class definition) and can be only initialized in those definitions".

Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?

If the data members are specific to the class, why are they declared at the global namespace scope and not some scope relevant to their class?

解决方案

Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?

Most likely because C++ has separate translation units. The compiler needs to pick an object file where the initialization logic for those symbols will be placed. Forcing this to be in a specific source file makes that decision easy for the compiler.

If the data members are specific to the class, why are they declared at the global namespace scope and not some scope relevant to their class?

Because that's just how C++ does class members. This is no different than other class members like member functions:

Header file:

namespace example {

// Class declared in header
struct some_class
{
    // Member variable
    static float example;
    // Member function
    void DoStuff() const;
};

}

Source file:

namespace example {

    // Implement member variable
    float some_class::example = 3.14159;
    // Implement member function
    void some_class::DoStuff() const
    {
         //....
    }
}

There's a specific exception to allow static const integral members to be initialized in the header because it allows the compiler to treat them as compile-time constants. That is, you can use them to define sizes of arrays or other similar bits in the class definition.

这篇关于为什么非const,非int / enum静态数据成员必须在定义之外初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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