सबसे पहले, एक स्थिर सरणी से यादृच्छिक नाम पैदा करने के लिए एक बहुत ही सरल कार्यक्रम। उचित वर्ग कार्यान्वयन और नीचे पाया जा सकता है।
#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];
}
क्लास कार्यान्वयन
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;
}
स्रोत
2010-12-11 10:31:42
जवाब के लिए धन्यवाद, यह लेने के लिए एक स्वीकृत जवाब दिया है कि वे ठीक हो मुश्किल था, लेकिन मैं सिर्फ QStringList साथ चला गया पूरी तरह उत्तर दें क्योंकि यह अच्छी तरह से इस तथ्य के साथ फिट बैठता है कि मैं क्यूटी सीखने की कोशिश कर रहा हूं। – DaveJohnston
@ डेव: हालांकि मैं आपको समझ सकता हूं, फिर भी मैं जहां भी संभव हो, अधिक मानक और पोर्टेबल कोड लिखना पसंद करता हूं। भले ही यह इतना साफ न हो (सी ++ 03 उदाहरण)। – ybungalobill