在 C++ 类中初始化静态变量? [英] Initialize static variables in C++ class?

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

问题描述

我注意到类中的某些函数实际上并未访问该对象,因此我将它们设为 static.然后编译器告诉我他们访问的所有变量也必须是静态的——嗯,到目前为止还可以理解.我有一堆字符串变量,例如

I have noticed that some of my functions in a class are actually not accessing the object, so I made them static. Then the compiler told me that all variables they access must also be static – well, quite understandable so far. I have a bunch of string variables such as

string RE_ANY = "([^\n]*)";
string RE_ANY_RELUCTANT = "([^\n]*?)";

等等.然后我将它们全部设为 static const 因为它们永远不会改变.但是,我的程序只有在我将它们移出类时才会编译:否则,MSVC++2010 会抱怨只有静态常量整数变量可以在类中初始化".

and so on in the class. I have then made them all static const because they never change. However, my program only compiles if I move them out of the class: Otherwise, MSVC++2010 complains "Only static constant integral variables may be initialized within a class".

那很不幸.有解决方法吗?我想把他们留在他们所属的班级里.

Well that's unfortunate. Is there a workaround? I would like to leave them inside the class they belong to.

推荐答案

它们不能在类内部初始化,但可以在类外部初始化,在源文件中:

They can't be initialised inside the class, but they can be initialised outside the class, in a source file:

// inside the class
class Thing {
    static string RE_ANY;
    static string RE_ANY_RELUCTANT;
};

// in the source file
string Thing::RE_ANY = "([^\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\n]*?)";

更新

我刚刚注意到你问题的第一行 - 你不想想让这些函数static,你想让它们const.使它们 static 意味着它们不再与对象相关联(因此它们不能访问任何非静态成员),并使数据静态意味着它将与此类型的所有对象共享.这很可能不是您想要的.使它们 const 仅仅意味着它们不能修改任何成员,但仍然可以访问它们.

I've just noticed the first line of your question - you don't want to make those functions static, you want to make them const. Making them static means that they are no longer associated with an object (so they can't access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const simply means that they can't modify any members, but can still access them.

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

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