Create objects in conditional c++ statements

前端 未结 7 1280
悲哀的现实
悲哀的现实 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:49

    First off, you cannot create an object within a conditional statement and use it after the conditional statement: the two branches of the conditional statement create a scope each and any object created within in destroyed a the end of the branch. That is, you need to come up with a different approach. The simplest approach is probably to delegate the creation of the object to a function which returns the objects as appropriate:

    Report makeReport() {
        if (enter_company_name()) {
            ...
            return Report(name, company);
        }
        return Report();
    }
    
    ...
    Report report = makeReport();
    

    An alternative approach is to use the ternary operator to conditonally create the Report one way or another:

    bool get_company_name = enter_company_name();
    std::string name(get_company_name? read_name(): "");
    std::string company(get_company_name? read_company(): "");
    Report report = get_company_name? Report(name, company): Report();
    

    All of these approaches assume that the Report class is actually copyable.

提交回复
热议问题