Create objects in conditional c++ statements

前端 未结 7 1262
悲哀的现实
悲哀的现实 2020-12-06 01:33

I am learning c++, and I just got to the object oriented chapter. I have a question about creating objects inside if statements.

The problem I\'m working on says

7条回答
  •  自闭症患者
    2020-12-06 02:02

    The simplest thing that comes to mind is performing a little refactoring on the code flow. Create a function that processes the input and returns the constructed object:

    Report loadReport() {
        if (user_input()) {
            // read input
            return Report(name,company);
        } else {
            return Report();
        }
    }
    

    Then call the function from main. The small change in the design is the introduction of a function whose single responsibility is creating a Report from user input, which actually makes sense as a function.

提交回复
热议问题