En primer lugar, un programa muy simple para la generación de nombres al azar a partir de una matriz estática. La implementación correcta de la clase se puede encontrar más abajo.
#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];
}
implementación de la clase
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;
}
Gracias por la respuesta, era difícil escoger una respuesta aceptada dado que todos ellos están bien, pero fuimos con la QStringList Responda puramente porque encaja muy bien con el hecho de que estoy tratando de aprender Qt. – DaveJohnston
@Dave: Aunque puedo comprenderte, prefiero escribir un código más estándar y portátil cuando sea posible. Incluso si no es tan limpio (el ejemplo de C++ 03). – ybungalobill