初始化全局变量类 [英] Initializing global variable class

查看:150
本文介绍了初始化全局变量类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对这样一个基本问题道歉,但我不能弄清楚。我知道你可以初始化这样的类:

Apologies for such a basic question but I can't figure it out. I know you can initialize a class like this:

QFile file("C:\\example");

但是如何从全局变量初始化它呢?例如:

But how would you initialize it from a global variable? For example:

QFile file; //QFile class

int main()
{
    file = ?? //need to initialize 'file' with the QFile class
}


推荐答案

1。直接回答



如果类是可分配的/可复制的,可以写

1. Straightforward answer

If the class is assignable/copy constructible you can just write

QFile file; //QFile class

int main()
{
    file = QFile("C:\\example");
}



2。使用间接



如果没有,您必须使用其他选项:

2. Use indirection

If not, you'll have to resort to other options:

QFile* file = 0;

int main()
{
    file = new QFile("C:\\example");

    //
    delete file;
}

或使用 boost :: optional< QFile> std :: shared_ptr< QFile> boost :: scoped_ptr< QFile>

由于静态初始化Fiasco 您可能想要编写这样的函数:

Due to the Static Initialization Fiasco you could want to write such a function:

static QFile& getFile()
{ 
    static QFile s_file("C:\\example"); // initialized once due to being static
    return s_file;
}

C ++ 11使得这样的函数局部静态初始化线程安全(引用C ++ 0x草案n3242,§6.7:)

C++11 made such a function-local static initialization thread safe as well (quoting the C++0x draft n3242, §6.7:)

这篇关于初始化全局变量类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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