如何在 C++ 中初始化私有静态成员? [英] How to initialize private static members in C++?

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

问题描述

在 C++ 中初始化私有静态数据成员的最佳方法是什么?我在头文件中尝试过这个,但它给了我奇怪的链接器错误:

What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:

class foo
{
    private:
        static int i;
};

int foo::i = 0;

我猜这是因为我无法从类外部初始化私有成员.那么最好的方法是什么?

I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?

推荐答案

类声明应该在头文件中(如果不共享则在源文件中).
文件:foo.h

The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h

class foo
{
    private:
        static int i;
};

但是初始化应该在源文件中.
文件:foo.cpp

But the initialization should be in source file.
File: foo.cpp

int foo::i = 0;

如果初始化在头文件中,那么每个包含头文件的文件都会有一个静态成员的定义.因此,在链接阶段,您将收到链接器错误,因为初始化变量的代码将在多个源文件中定义.static int i 的初始化必须在任何函数之外完成.

If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files. The initialisation of the static int i must be done outside of any function.

注意: Matt Curtis:指出如果静态成员变量是 const int 类型(例如 int, bool, char).然后就可以直接在头文件的类声明中声明和初始化成员变量:

Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const int type (e.g. int, bool, char). You can then declare and initialize the member variable directly inside the class declaration in the header file:

class foo
{
    private:
        static int const i = 42;
};

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

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