所以当我运行这个程序时,
#include<iostream>
#include<ctime>
float ex, ey;
class Enemy
{
public:
float x, y;
Enemy()
{
x = ex;
y = ey;
}
void showLocation()
{
std::cout<<x<<" , "<<y<<std::endl;
}
};
int main()
{
Enemy e;
for(int i = 0;i<5,i++;)
{
ex = rand() % 5 + 1;
ey = rand() % 5 + 1;
e.showLocation();
}
}我什么也没得到,我做错什么了吗?我得到一个空格,然后上面写着,“进程退出-返回代码0”
发布于 2022-04-25 22:20:28
对象e是在for循环之前初始化的。因此,它的数据成员x和y被默认构造函数设置为0.0f (全局变量ex和ey隐式地为零初始化),并且不再更改。
Enemy e;
for(int i = 0;i<5,i++;)
{
ex = rand() % 5 + 1;
ey = rand() % 5 + 1;
e.showLocation();
}您需要在for循环中声明对象,例如
for(int i = 0;i<5,i++;)
{
ex = rand() % 5 + 1;
ey = rand() % 5 + 1;
Enemy e;
e.showLocation();
}在这种情况下,在for循环的每次迭代中,将创建一个新的对象e数据成员,该对象的数据成员将由全局变量ex和ey的计算值初始化。
https://stackoverflow.com/questions/72006163
复制相似问题