问题
Possible Duplicate:
In C++ why have header files and cpp files?
I was wondering if it is advisable to write a the whole class c++ in a header file ? and use include to include the class, in a similar way that java does its oop programming. Is it a bad style ? can anyone recommend me a "good" C++ oop style guide ? Also I wondering if template programming is what they really mean when they talk about someone who is experienced in c++.
回答1:
Including function definitions in a header file has some knock on effects and it's generally avoided. Functions defined in this manner are likely to be inlined, which will increase the size of your executable which can effect performance (in a positive or a negative way). Also, doing this can increase your build times, as having all definitions in line will increase the likelihood that you have to include additional files, etc.
The general practice is to put a classes interface in a header file (.h
) and its implementation in a implementation file (.cpp
).
In some cases it's required to have all of the code available -- as is the case with templates. The STL makes extensive use of templates and implementations of functions are included in the header files by necessity.
回答2:
Put public class and functions declaration in .h Put definitions and everything else in .cpp
.h is your interface, .cpp is your implementation.
回答3:
It's always better style to separate the declaration from the implementation, especially for more complicated functions.
Templates are something a little bit more advanced.
A good primer is: http://www.cplusplus.com/doc/tutorial/classes/
来源:https://stackoverflow.com/questions/7070192/class-implementation-in-a-header-file-bad-style