简体   繁体   English

为什么不能在主体或头文件中的类中初始化静态成员?

[英]Why can't initialize the static member in a class in the body or in the header file?

Could any body offer me any reason about that? 有人能为我提供任何理由吗?

If we do it like that, what's the outcome? 如果我们那样做,结果是什么? Compile error? 编译错误?

It is just a limitation in the language it self. 这只是其自身语言的限制。 Hopefully, when C++0x becomes reality, this limitation would go away. 希望当C ++ 0x成为现实时,这种限制将消失。

I think this page gives a somehow good reason : 我认为此页面提供了某种很好的理由

One of the trickiest ramifications of using a static data member in a class is that it must be initialized, just once, outside the class definition, in the source file. 在类中使用静态数据成员的最棘手的后果之一是,必须在类定义之外仅在源文件中对其进行一次初始化。 This is due to the fact a header file is typically seen multiple times by the compiler. 这是由于编译器通常会多次查看头文件。 If the compiler encountered the initialization of a variable multiple times it would be very difficult to ensure that variables were properly initialized. 如果编译器多次遇到变量的初始化,将很难确保变量已正确初始化。 Hence, exactly one initialization of a static is allowed in the entire program. 因此,在整个程序中只允许静态的一个初始化。

The problem is that static initialization isnt just initialization, it is also definition . 问题是静态初始化不只是初始化,它还是定义 Take for example: 举个例子:

hacks.h : hacks.h:

class Foo
{
public:
    static std::string bar_;
};

std::string Foo::bar_ = "Hello";

std::string GimmeFoo();

main.cpp : main.cpp:

#include <string>
#include <sstream>
#include <iostream>

#include "hacks.h"

using std::string;
using std::ostringstream;
using std::cout;

int main()
{

    string s = GimmeFoo();
    return 0;
}

foo.cpp : foo.cpp:

#include <string>
#include <sstream>
#include <iostream>

#include "hacks.h"

using std::string;
using std::ostringstream;
using std::cout;

string GimmeFoo()
{
    Foo foo;
    foo;
    string s = foo.bar_;

    return s;
}

In this case, you can't initialize Foo::bar_ in the header because it will be allocated in every file that #include s hacks.h. 在这种情况下,您无法在标头中初始化Foo::bar_ ,因为它将在#include s hacks.h中的每个文件中分配。 So there will be 2 instances of Foo.bar_ in memory - one in main.cpp, and one in foo.cpp. 因此,内存中将有2个Foo.bar_实例-一个在main.cpp中,一个在foo.cpp中。

The solution is to allocate & initialize in just one place: 解决方案是仅在一个位置分配和初始化:

foo.cpp : foo.cpp:

...
std::string Foo::bar_ = "Hello";
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM