我正在通过为乐趣设置的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