header file and source file

Header file header file, the suffix is ​​.h, the header file is responsible for the definition of classes, function declarations, and definitions of constants

Source file source file, the suffix is ​​.cpp, the implementation of the function

The main function is to separate the declaration and implementation of the function. If you want to give the class and function to others for use, but do not want others to know the source code of the class and function, directly give the header file of the class or function to the other party.

Generally, a class is equipped with a header file .h for declaration and a .cpp source file for implementation.

There are two classes in the figure below. Each class has a header file declaration and a source file implementation.

 Here's an example:

(1) Declare the class in the header file MyClass.h

  In this file, the constructor, destructor, and an ordinary function called MyMethod are declared for this class.

It is also declared that there is a private attribute in this class called data

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass {
public:
  MyClass();  // 构造函数
  ~MyClass(); // 析构函数

  void MyMethod(); // 自定义方法

private:
  int data; // 私有成员变量
};

#endif // MYCLASS_H

(2) Implement the class in the source file MyClass.cpp

First you need to introduce this header file MyClass.h

Then the three functions of this class (constructor, destructor, member function MyMethod) are implemented respectively.

#include "MyClass.h"
#include <iostream>

MyClass::MyClass() {
   data = 0; // 初始化私有成员变量
}

MyClass::~MyClass() {
  // 析构函数
}

void MyClass::MyMethod() {
  std::cout << "调用了 MyMethod() 方法" << std::endl;
}

Guess you like

Origin blog.csdn.net/weixin_47414034/article/details/131167297