c++ - 构造函数和析构函数 - C++

标签 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();
};

最佳答案

似乎没有循环/递归的唯一可能的方法是这样的:

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/

相关文章:

c++ - 如何在 Go 中使用 C++

c++ - C++ 中的数组声明、大小定义和销毁

c++ - 奇怪的对象分配行为 c++

c++ - 为什么 C++ 中的析构函数以与初始化相反的顺序释放内存?

c++ - 析构函数崩溃

c++ - 为什么我的程序没有触及我所做的功能?

c++ - 在 Fedora 上编译 C++ 程序

c++ - 使用 boost::hana::is_valid 验证有效调用存在困难

java - Java 中的继承和构造函数

c++ - 我可以调用虚函数来初始化基类子对象吗?