Create objects in conditional c++ statements

前端 未结 7 1290
悲哀的现实
悲哀的现实 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 01:50

    I don't know if I understood your question correctly but can't you just declare report before the if/else block and then initialize inside it?

    Report header;
    
    if (...) {
      header = Report();
    else
      header = Report(name,company);
    

    Or in a shorter way:

    Report header; // calls default constructor
    
    if (shouldInitializeWithParams) {
      header = Report(name,company);
    }
    

    Of course this requires you to have the empty constructor defined.

提交回复
热议问题