初始化全局变量类
对于这样一个基本问题表示歉意,但我无法弄清楚。我知道你可以像这样初始化一个类:
QFile file("C:\\example");
但是你如何从全局变量初始化它呢?例如:
QFile file; //QFile class
int main()
{
file = ?? //need to initialize 'file' with the QFile class
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
1. 直接回答
如果类是可分配/可复制构造的,您可以只写
2. 使用间接
如果不是,您将不得不求助于其他选项:
或使用
boost::optional
,std::shared_ptr
、boost::scoped_ptr
等3. 使用单例相关模式:
由于 静态初始化惨败,您可能想要编写这样一个函数:
C++11 也使这样一个函数局部静态初始化线程安全(引用 C++0x 草案 n3242,§6.7:)
1. Straightforward answer
If the class is assignable/copy constructible you can just write
2. Use indirection
If not, you'll have to resort to other options:
Or use
boost::optional<QFile>
,std::shared_ptr<QFile>
,boost::scoped_ptr<QFile>
etc.3. Use singleton-related patterns:
Due to the Static Initialization Fiasco you could want to write such a function:
C++11 made such a function-local static initialization thread safe as well (quoting the C++0x draft n3242, §6.7:)
同样的方式:
所有全局对象的构造函数在调用
main()
之前执行(对于析构函数则相反)。The same way:
The constructors of all global objects execute before
main()
is invoked (and inversely for destructors).顺便说一句,你写道:
你不能初始化一个类。您创建并初始化对象,而不是类。
By the way, you wrote:
You can not initialize a class. You create and initialize object, not a class.
是否使用全局变量或其他变量完全取决于您。
对于全局变量,您可以在文件中全局定义它,然后在函数中初始化它,如下所示,请确保正确编写复制构造函数。
但是,如果您使用全局指针会更好,
请注意,如果您仅在文件内使用此全局变量,则可以将其设为静态变量。那么它就仅限于文件本身。因此您可以最大限度地减少全局变量的坏。
It is totally up to you to decide whether you use a global variable or some thing else.
For a global variable you can define it in globally in the file and then initialize it in function as below, make sure that you write copy constructor properly.
But, it is better if you use global pointer,
Note, if you are using this global variable only within the file, you can make it a
static
variable. Then it is limited to file itself. So you can minimize the bad of global variables.