在c ++中的静态构造函数 [英] Static constructor in c++

查看:107
本文介绍了在c ++中的静态构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题在面试中询问我:

This question was asked to me in an interview:

什么是静态构造函数?

它存在于C ++?如果是,请以示例解释。

Does it exist in C++? If yes, please explain with an example.

推荐答案

C ++没有静态构造函数,但是可以使用静态实例的嵌套类。

C++ doesn’t have static constructors but you can emulate them using a static instance of a nested class.

class has_static_constructor {
    friend class constructor;

    struct constructor {
        constructor() { /* do some constructing here … */ }
    };

    static constructor cons;
};

// C++ needs to define static members externally.
has_static_constructor::constructor has_static_constructor::cons;

这篇关于在c ++中的静态构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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