use*_*400 3 c++ constructor destructor
我需要编写一个程序,在屏幕上打印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();
};
Run Code Online (Sandbox Code Playgroud)
Ele*_*tal 15
似乎没有循环/递归的唯一方法是这样的:
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];
}
Run Code Online (Sandbox Code Playgroud)
这实际上只是一个愚蠢的技巧,因为编译器必须运行每个星的构造函数来初始化数组,然后运行EACH star的析构函数,因为它超出了范围.
这也是一个糟糕的伎俩,因为主要功能中的所有工作都是不透明和不可见的.在这种情况下使用循环显然会更好,并且在这样的析构函数中放置延迟实际上是令人困惑和不可维护的.
这不是运行时递归:
template<int N>
struct Star
{
Star() { DrawAtRandomPlace(); }
~Star() { RemoveSlowly(); }
Star<N-1> star;
};
template<> struct Star<0> {};
int main()
{
Star<100> stars;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将生成100个不同的Star模板实例.RAII将保证绘图和删除的顺序.