为什么不能在主体或头文件中的类中初始化静态成员? [英] Why can't initialize the static member in a class in the body or in the header file?

查看:560
本文介绍了为什么不能在主体或头文件中的类中初始化静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何机构可以向我提供任何理由吗?

Could any body offer me any reason about that?

如果我们这样做,结果是什么?编译错误?

If we do it like that, what's the outcome? Compile error?

推荐答案

问题是静态初始化只是初始化,它也是定义。例如:

The problem is that static initialization isnt just initialization, it is also definition. Take for example:

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;
}

在这种情况下,您不能初始化 Foo :: bar _ ,因为它将在 #include s hacks.h的每个文件中分配。因此,在内存中将有2个实例 Foo.bar _ - 一个在main.cpp中,一个在foo.cpp中。

In this case, you can't initialize Foo::bar_ in the header because it will be allocated in every file that #includes hacks.h. So there will be 2 instances of Foo.bar_ in memory - one in main.cpp, and one in foo.cpp.

解决方案是分配&仅在一个位置初始化:

The solution is to allocate & initialize in just one place:

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

这篇关于为什么不能在主体或头文件中的类中初始化静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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