我需要编写一个程序,在屏幕上(随机位置)打印 100 颗星星,然后星星慢慢消失——一个接一个。我不允许使用循环或递归。 我试过使用构造函数和析构函数,但我无法让星星一个接一个地消失(而不是全部消失)。 有什么想法吗?
谢谢, 李
抱歉 - 忘了说我正在使用 C++
我当前的访问违反无用代码:
class star {
int x;
int y;
public:
star(){
x = rand()%80;
y = rand()%80;
PaintcharOnRandomLocation('*',x,y);
};
~star(){
PaintcharOnRandomLocation(' ',x,y);
};
};
class printAll{
star* arr;
public:
printAll(){
arr = new star[100];
};
~printAll(){
delete[] arr;
};
};
void doNothing(printAll L){
};
void main()
{
srand ( time(NULL) );
doNothing(printAll());
getch();
};
最佳答案
似乎没有循环/递归的唯一可能的方法是这样的:
class Star
{
Star()
{
//constructor shows star in a a random place
}
~Star()
{
//destructor removes star and sleeps for a random amount of time
}
};
int main()
{
Star S[100];
}
这实际上只是一个愚蠢的技巧,因为编译器必须为每个星运行构造函数来初始化数组,然后在每个星超出范围时运行析构函数。
这也是一个糟糕的技巧,因为进入主函数的所有工作都是不透明和不可见的。显然,在这种情况下使用循环会更好,并且像这样将延迟放在析构函数中确实令人困惑且无法维护。
关于c++ - 构造函数和析构函数 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3557030/