我该如何在班上实现一个静态的字符串集合

Dav*_*ton 8 c++ qt static constants

我是C++的新手,所以这可能是一个容易回答的问题.我正在编写一个类(Person),当创建Person时,应该从预定义名称的集合中为其分配一个随机名称.所以在Person类中我想定义一些我可以随机访问的静态字符串集合,因此我还需要知道它有多少.

我也在这里使用Qt,所以解决方案最好是使用标准库或Qt库中的东西.

我来自Java背景和Java,我可能会做类似的事情:

private static final String[] NAMES = { "A", "B" };
Run Code Online (Sandbox Code Playgroud)

在这种情况下,相同的是什么?

小智 24

你可以使用QStringList.

Person.h:

class Person
{
private:
    static QStringList names;
};
Run Code Online (Sandbox Code Playgroud)

Person.cpp:

QStringList Person::names = QStringList() << "Arial" << "Helvetica" 
    << "Times" << "Courier";
Run Code Online (Sandbox Code Playgroud)


ybu*_*ill 9

假设C++ 03:

class YourClass {
    static const char*const names[];
    static const size_t namesSize;
};

// in one of the translation units (*.cpp)
const char*const YourClass::names[] = {"A", "B"};
const size_t YourClass::namesSize = sizeof(YourClass::names) / sizeof(YourClass::names[0]);
Run Code Online (Sandbox Code Playgroud)

假设C++ 0x:

class YourClass {
    static const std::vector<const char*> names;
};

// in one of the translation units (*.cpp)
const vector<const char*> YourClass::names = {"A", "B"};
Run Code Online (Sandbox Code Playgroud)

当然,您可以使用您喜欢的字符串类型而不是const char*.