我正在通過爲樂趣設置的C++問題。我正在創建一個將對象添加到具有隨機特徵的類的循環。其中一個隨機特徵是對象名稱。我有一個程序爲類對象隨機生成名稱,但我無法弄清楚如何將這些名稱分配給類對象。C++命名類具有變量的對象
這裏是我的類,它的構造函數:
#include "stdafx.h"
#include <iostream>
#include "windows.h"
#include <string>
#include <sstream>
#include <array>
#include <time.h>
#include <conio.h>
class Bunny
{
public:
char fname;
int sex, age, color, status;
Bunny(int, int, int, int);
int s() { return (sex); }
int a() { return (age); }
int c() { return(color);}
int st() { return (status);}
};
Bunny::Bunny(int s, int a, int c, int st)
{
sex = s;
age = a;
color = c;
status = st;
}
這是產生「兔子」的信息循環。
std::string name;
for (n = 0; n < 1; n++)
{
int num = std::rand() % 5;
int s = std::rand() % 2;
std::string f = "Susan"; //this is normally a function which randomly gives names
name = f;
int a = 0;
int c = std::rand() % 5;
int st;
if (rand() % 50 == 43) st = 1; else st = 0;
Bunny name(s, a, c, st);
}
,如果它是工作的權利,應該讓一個成員是這樣的:
Bunny Susan(1, 0, 2, 0);
這不工作,因爲它創建了一個名爲「名」,而不是「蘇珊」一類的對象。我如何通過變量爲類對象分配名稱,而不是在代碼中手動分配名稱。
你不能那樣做。 – abelenky 2014-08-27 22:14:44
C++類不能在運行時修改。 – Barmar 2014-08-27 22:15:08
使用'std :: map'將字符串像「Susan」'寫入數據。 – Barmar 2014-08-27 22:16:06