8

I am very new to C++ so this might be an easy question to answer. I am writing a class (Person) and when a Person is created it should be assigned a random name from a collection of predefined names. So within the Person class I would like to define some sort of static collection of strings that I can access randomly and therefore I would also need to know how many there are.

I am using Qt here too, so the solution should preferably be using things from the standard library or the Qt library.

I am from a Java background and in Java I would probably do something like:

private static final String[] NAMES = { "A", "B" };

What would be the equivalent in this case?

DaveJohnston
  • 10,031
  • 10
  • 54
  • 83

3 Answers3

24

You could use QStringList.

Person.h:

class Person
{
private:
    static QStringList names;
};

Person.cpp:

QStringList Person::names = QStringList() << "Arial" << "Helvetica" 
    << "Times" << "Courier";
feedc0de
  • 3,646
  • 8
  • 30
  • 55
9

Assuming 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]);

Assuming 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"};

And of course you can use your favorite string type instead of const char*.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • Thanks for the answer, it was hard to pick an accepted answer given that they are all right, but I just went with the QStringList answer purely because it fits in nicely with the fact that I am trying to learn Qt. – DaveJohnston Dec 11 '10 at 10:52
  • 1
    @Dave: Although I can understand you, I still prefer writing more standard and portable code where possible. Even if it's not so neat (the C++03 example). – Yakov Galka Dec 11 '10 at 11:01
4

First, a very simple program for generating random names from a static array. The proper class implementation can be found further down.

#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>

// import the std namespace (to avoid having to use std:: everywhere)
using namespace std;
// create a constant array of strings
static string const names[] = { "James", "Morrison",
                                "Weatherby", "George", "Dupree" };
// determine the number of names in the array
static int const num_names = sizeof(names)/sizeof(names[0]);

// declare the getRandomName() function
string getRandomName();

// standard main function
int main (int argc, char * argv[])
{
    // seed the random number generator
    srand(time(0));
    // pick a random name and print it
    cout << getRandomName() << endl;
    // return 0 (no error)
    return 0;
}

// define the getRandomName() function
string getRandomName()
{
    // pick a random name (% is the modulo operator)
    return names[rand()%num_names];
}

Class implementation

Person.h

#ifndef PERSON_
#define PERSON_

#include <string>

class Person
{
    private:
        std::string p_name;
    public:
        Person();
        std::string name();
};

#endif

Person.cpp

#include "Person.h"
#include <stdlib.h>

using namespace std;

static string const names[] = { "James", "Morrison",
                                "Weatherby", "George", "Dupree" };
static int const num_names = sizeof(names)/sizeof(names[0]);

Person::Person() : p_name(names[rand()%num_names]) { }
string Person::name() { return p_name; }

main.cpp

#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include "Person.h"

using namespace std;

int main (int argc, char * argv[])
{
    // seed the random number generator
    srand(time(0));

    // create 3 Person instances
    Person p1, p2, p3;

    // print their names
    cout << p1.name() << endl;
    cout << p2.name() << endl;
    cout << p3.name() << endl;

    // return 0 (no error)
    return 0;
}
e.James
  • 116,942
  • 41
  • 177
  • 214
  • A good explanation, but `using namespace std;` is a bad idea and can cause a whole bunch of problems, many of which have been posted here on SO due to namespace conflicts. It takes next-to-no-time to type `std::`. – Moo-Juice Dec 11 '10 at 10:41
  • 3
    using "`using namespace std;`" is bad *in a header file*. Using it in a source file is perfectly fine. – e.James Dec 11 '10 at 10:45
  • Although, naturally, the debate rages on `:)` http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c – e.James Dec 11 '10 at 10:48
  • Thanks for going the extra mile to work it all into a full sample. – DaveJohnston Dec 11 '10 at 10:49
  • @DaveJohnston: My pleasure. I know it can be difficult to make sense of it all when you are just starting out `:)` – e.James Dec 11 '10 at 11:06
  • @e.James , yeah you did go the extra mile :) Now I feel bad about mentioning `using namespace std;`... ugh :) – Moo-Juice Dec 11 '10 at 19:02
  • @Moo-Juice: No worries at all. It is an important distinction to make. `using namespace std;` in a header is a terrible idea, so it is good to have the issue out in the open. – e.James Dec 11 '10 at 20:02