Đầu tiên, một chương trình rất đơn giản để tạo ra cái tên ngẫu nhiên từ một mảng tĩnh. Việc thực hiện lớp thích hợp có thể được tìm thấy tiếp tục xuống.
#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];
}
thực hiện Lớp
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;
}
Nguồn
2010-12-11 10:31:42
Cảm ơn cho câu trả lời, thật khó để chọn một câu trả lời chấp nhận cho rằng họ là tất cả đúng, nhưng tôi chỉ đi với QStringList trả lời hoàn toàn bởi vì nó phù hợp với thực tế là tôi đang cố gắng học hỏi Qt. – DaveJohnston
@Dave: Mặc dù tôi có thể hiểu bạn, tôi vẫn thích viết mã chuẩn và di động hơn nếu có thể. Thậm chí nếu nó không gọn gàng (ví dụ C++ 03). – ybungalobill