c ++类声明中静态对象的初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10499582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:08:51  来源:igfitidea点击:

c++ initialization of static object in class declaration

c++static-members

提问by bryan sammon

I have a C++ class (class1) with a static object of another class (class2) as a private member.

我有一个 C++ 类(class1),另一个类(class2)的静态对象作为私有成员。

I know upon using the program I will have to initialize the static object, I can use a default constructor for this (undesired value).

我知道在使用程序时我必须初始化静态对象,我可以为此使用默认构造函数(不需要的值)。

Is it possible to initialize the static object to my desired value only once, and only if I create an object of the containing class (class1)?

是否可以仅将静态对象初始化为我想要的值一次,并且仅当我创建包含类(class1)的对象时?

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Seth Carnegie

Yes.

是的。

// interface

class A {

    static B b;
};

// implementation

B A::b(arguments, to, constructor); // or B A::b = something;

However, it will be initialised even if you don't create an instance of the Aclass. You can't do it any other way unless you use a pointer and initialise it once in the constructor, but that's probably a bad design.

但是,即使您不创建A类的实例,它也会被初始化。除非您使用指针并在构造函数中将其初始化一次,否则您不能以任何其他方式执行此操作,但这可能是一个糟糕的设计。

IF you really want tothough, here's how:

如果你真的想要,这里是如何:

// interface

class A {
    A() { 
        if (!Bptr)
            Bptr = new B(arguments, to, constructor);

        // ... normal code
    }

    B* Bptr;
};

// implementation

B* A::Bptr = nullptr;

However, like I said, that's most likely a bad design, and it has multithreading issues.

但是,就像我说的,这很可能是一个糟糕的设计,并且存在多线程问题。