Home > Backend Development > C++ > How to Separate C Class Declarations and Member Function Implementations into Header and Source Files?

How to Separate C Class Declarations and Member Function Implementations into Header and Source Files?

DDD
Release: 2025-01-02 13:01:43
Original
1012 people have browsed it

How to Separate C   Class Declarations and Member Function Implementations into Header and Source Files?

Separating Class and Member Functions into Header and Source Files

In C , classes can be declared and implemented in separate header and source files. This allows for easier management and organization of code.

Class Declaration in Header File:

The header file (.h) contains the class declaration, which includes the name, data members, and member function prototypes. Include guards are used to prevent multiple inclusions.

// A2DD.h
#ifndef A2DD_H
#define A2DD_H

class A2DD
{
public:
  A2DD(int x, int y);
  int getSum();
};

#endif
Copy after login

Class Implementation in Source File:

The source file (.cpp) contains the implementation of the class's member functions. The functions are defined using the class's scope operator (::).

// A2DD.cpp
#include "A2DD.h"

A2DD::A2DD(int x, int y)
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}
Copy after login

Syntax for Using the Class:

To use the class, include the header file in the main file. Instantiation of the class and access to its member functions is done as follows:

// main.cpp
#include "A2DD.h"

int main()
{
  A2DD a(1, 2);
  int sum = a.getSum();
  return 0;
}
Copy after login

The above is the detailed content of How to Separate C Class Declarations and Member Function Implementations into Header and Source Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template