How many constructors should a class have?

前端 未结 16 1913
一向
一向 2021-02-04 12:34

I\'m currently modifying a class that has 9 different constructors. Now overall I believe this class is very poorly designed... so I\'m wondering if it is poor design for a clas

16条回答
  •  清酒与你
    2021-02-04 12:38

    I generally have one, which may have some default parameters. The constructor will only do the minimum setup of the object so it's valid by the time it's been created. If I need more, I'll create static factory methods. Kind of like this:

    class Example {
    public:
      static FromName(String newname) { 
        Example* result = new Example();
        result.name_ = newname;
        return result;
      }
      static NewStarter() { return new Example(); }
    
    private:
      Example();
    }
    

    Okay that's not actually a very good example, I'll see if I can think of a better one and edit it in.

提交回复
热议问题