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

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

问题描述

我注意到我的一些类的函数实际上不访问对象,所以我让他们 static 。然后编译器告诉我,他们访问的所有变量也必须是静态的 - 很好,到目前为止是很容易理解的。我有一堆字符串变量,如

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

等。我已经让他们所有 static const ,因为他们从来没有改变。但是,我的程序只编译如果我把它们移出类:否则,MSVC ++ 2010抱怨只有静态常量积分变量可以在类内初始化。



解决方案

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

  //类中的
类Thing {
static string RE_ANY;
static string RE_ANY_RELUCTANT;
};

//在源文件中
string Thing :: RE_ANY =([^ \\\\
] *);
string Thing :: RE_ANY_RELUCTANT =([^ \\\\
] *?);

更新



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


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]*?)";

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]*?)";

Update

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天全站免登陆