Separating Class Declaration and Implementation into Header and Source Files
Storing class declarations and member function implementations in separate header and source files is essential for modular and well-structured programming. Take, for instance, the following A2DD class:
class A2DD { private: int gx; int gy; public: A2DD(int x, int y); int getSum(); };
Class Declaration in Header File
To separate the class declaration from its implementation, create a header file named A2DD.h, which contains only the class declaration without the implementation of the member functions. It should include include guards to prevent multiple inclusions:
// A2DD.h #ifndef A2DD_H #define A2DD_H class A2DD { public: int gx; int gy; public: A2DD(int x, int y); int getSum(); }; #endif
Note that as C class members are private by default, we have omitted the private access specifier.
Member Function Implementation in Source File
Next, create a corresponding source file named A2DD.cpp that contains the implementations of the member functions:
// A2DD.cpp #include "A2DD.h" A2DD::A2DD(int x, int y) { gx = x; gy = y; } int A2DD::getSum() { return gx + gy; }
The header file A2DD.h needs to be included in the source file A2DD.cpp to provide the necessary definitions.
By separating the class declaration and implementation into different files, you can effectively manage class definitions and reduce compilation time. This approach promotes code maintainability, reusability, and collaboration among developers.
The above is the detailed content of How to Separate Class Declaration and Implementation in C Header and Source Files?. For more information, please follow other related articles on the PHP Chinese website!