简体   繁体   中英

Definition of function which is the class member

I have two functions, which are private members of class "Data":

class Date
{
private:
    bool leapYear(int y);
    void fillDate(int d, Month m, int y);
};

So, where is the best to define this functions:

  • in class definition;
  • in header file outside the class;
  • or in ".cpp" file?

You have the choice here. Here are some ideas to make your mind:

  • Inlining for speed is no longer a concern, since compilers are now good at link time optimization. So performance should not be a decision factor here (compilation speed matters too, but this is another bag of worms).
  • Small inline member functions, defined inside the class, may be an easy way to "document" what the class does. Also, this tends to keep the implementation localized, which is comfortable when reading the code. Don't overdo it however.
  • Large functions should in principle go into their own file, or at least outside the class definition, since they clutter the class definition code for no good reason. Template code is no exception.
  • Pimpl have advantages/disadvantages too, but here I don't see any good reason to introduce such beasts in your simple case. They are used typically to reduce dependencies between header files.

Here, if the implementation is small, you can write the code inline, inside the class. But you should put them in their own implementation (".cpp") file, if the logic is complex.

You can also start inline, and when the code has settled to something more complex, move the implementation to its own file.

我强烈建议您不要考虑选项2.如果您将此文件包含在多个实现文件中,则链接器会出现“多个定义”错误,因为定义将(由预处理器)复制到每个.cpp文件中。

My personal philosophy about this is to put all function definitions into the implementation (.cpp) file, because, first of all, it separates declarations (+ documentation) from definitions which adds to code clarity IMO, and, secondly, having all definitions in one place (the implementation file) makes it easier for me to find functions. In my experience it was always quite a nuisance to have to switch between header and implementation files to see whether this particular function I'm looking for was inlined / defined in the header or if it was in the implementation file. Having all function definitions in the implementation file means I know I will find the definition of any function in that file, and won't have to waste time switching and looking around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM