Calling a constructor to re-initialize object

前端 未结 12 1740
执笔经年
执笔经年 2020-12-04 15:01

is it possible to re-initialize an object of a class using its constructor?

12条回答
  •  [愿得一人]
    2020-12-04 15:44

    May-be not what you have in mind, but since you didn't mention what it is for, I suppose one answer would be that you'd do it by controlling scope and program flow.

    For example, you wouldn't write a game like this:

    initialize player
    code for level 1
    ...
    reinitialize player
    code for level 2
    ...
    etc
    

    Instead you'd strive for:

    void play_level(level_number, level_data) {
        Player player; //gets "re-initialized" at the beginning of each level using constructor
        //code for level
    }
    
    void game() {
        level_number = 1;
        while (some_condition) {
            play_level(level_number, level_data);
            ++level_number;
        }
     }
    

    (Very rough outline to convey the idea, not meant to be remotely compilable.)

提交回复
热议问题