在对象中构造 int 后从对象递增 int C++
Incrementing an int from an object after it's constructed in C++
我有一个游戏,每个转弯都会创建一个新的兔子对象。每个兔子都有一个年龄的年龄,我希望游戏中每个对象的每个传球都会增加年龄。
我为逐渐增加年龄的班级制作了一种方法,但似乎只会增加一次。
我如何继续?
class Bunny
{
private:
std::string sex, color, name;
int age;
public:
void agePlusOne(void);
Bunny();
~Bunny();
};
void Bunny::agePlusOne()
{
age += 1; // Or age++;
}
int main()
{
int the_time;
clock_t startTime = clock(); //Start timer
clock_t testTime;
clock_t timePassed;
double secondsPassed;
std::vector<Bunny> bunnies; //Bunny objects container
while (true)
{
testTime = clock();
timePassed = startTime - testTime;
secondsPassed = timePassed / (double)CLOCKS_PER_SEC;
the_time = (int)secondsPassed * -1;
if (the_time % 2 == 0) //This is what happens each turn
{
for (auto e : bunnies)
{
e.agePlusOne(); //All bunnies age one year
}
bunnies.push_back(Bunny()); //Adds bunny object to vector
}
}
//End of program
system("pause");
return 0;
}
这里的主要问题似乎是您在最内向的 for
循环中处理兔子向量的副本。当您写作:
for (auto e : bunnies)
{
// More code here
}
e
只是该位置的向量中的任何元素的副本,而不是原始元素本身。
如果您想修改向量中的元素,请通过参考访问它们,并相应地调用其突变器。例如:
for (auto & e : bunnies)
// ^
// Note the ampersand above.
{
int tempAge = e.get_age();
e.agePlusOne(); // Now this will change the internal state
// of `age` for this bunny.
// More code
}
这将修改实际对象,而不仅仅是复制。
相关文章:
- 在c++中访问int到类对象的映射时出错
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 包装一个对象并假装它是一个 int
- 类型为 'std::map< char,int > 的 <Swig 对象的代理
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- 类对象在 int main() 中'undefined'
- 如果类对象需要在 C++ 中转换为 int,为什么会调用 "operator bool()"?
- 为什么 int 对象和函数类型之间不明确?
- switch 语句和对象隐式 int 转换
- 如何从 pair<int、对象的向量中删除重复项>
- 对类似"struct {double, int}"对象使用reinterpret_cast进行对象访问
- 重载 + 运算符以使用 int 添加对象
- 如何在C 2D向量中找到对象(而不是int)的位置
- 如何掩盖对象数组的数据类型字符串到C 中的INT
- jfieldid int对对象无效
- 在 c++ 中声明 int 对象
- 根据C++标准,int 变量是对象吗?
- 声明 Windows API 结构 (DCB) 的对象 - 错误 C4430:缺少类型说明符 - 假定为 int
- 如何使用 Android NDK 创建 Java 对象(int[])
- 拔河:将一组n个对象int划分为多个子集