How should I order the members of a C++ class?

后端 未结 15 1804
Happy的楠姐
Happy的楠姐 2020-12-04 11:50

Is it better to have all the private members, then all the protected ones, then all the public ones? Or the reverse? Or should there be multiple private, protected and pub

15条回答
  •  时光说笑
    2020-12-04 12:37

    In practice, it rarely matters. It's primarily a matter of personal preference.

    It's very popular to put public methods first, ostensibly so that users of the class will be able to find them more easily. But headers should never be your primary source of documentation, so basing "best practices" around the idea that users will be looking at your headers seems to miss the mark for me.

    It's more likely for people to be in your headers if they're modifying the class, in which case they should care about the private interface.

    Whichever you choose, make your headers clean and easy to read. Being able to easily find whatever info I happen to be looking for, whether I'm a user of the class or a maintainer of the class, is the most important thing.

提交回复
热议问题