Zuerst wird ein sehr einfaches Programm für zufällige Namen aus einer statischen Array zu erzeugen. Die richtige Klassenimplementierung finden Sie weiter unten.
#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];
}
Klasse Implementierung
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;
}
Danke für die Antwort, es war schwer, eine akzeptierte Antwort gegeben zu wählen, dass sie alles in Ordnung, aber ich ging einfach mit dem QStringList antworte rein, weil es gut zu der Tatsache passt, dass ich versuche Qt zu lernen. – DaveJohnston
@Dave: Obwohl ich Sie verstehen kann, bevorzuge ich immer noch mehr Standard und tragbaren Code wo möglich zu schreiben. Auch wenn es nicht so ordentlich ist (das C++ 03-Beispiel). – ybungalobill