#ifndef #define #endif的用法
看懂了一点点,存个挡
此语法用于C/C++中防止头文件重复引用,举个例子:
有两个类:圆类(Circle) 和点类(Point),并且将两个类分头文件进行定义,并且圆类中定义圆心时需要用到点类,那么点类和圆类的定义分别大致如下:
//点类,point.h
#include <iostream>
using namespace std;
class Point {
public:
void setX(int x);
int getX();
void setY(int y);
int getY();
private:
int m_X;
int m_Y;
};
//圆类,circle.h
#include <iostream>
#include "point.h"
using namespace std;
class Circle {
public:
void setR(int r);
int getR();
void setCenter(Point p);
Point getCenter();
private:
int m_R; //半径
Point m_center;
};
当你在main中进行测试的时候,既要包含圆类,也要包含点类,当编译圆类时发现圆类中包含了点类,因此会去编译点类,当接着编译到点类时就会出现重复包含的问题:circle.h中包含了一次point.h, main中又包含了一次。此时就可以在point.h中加入此语法,改成如下:
#ifndef _POINT_H_
#define _POINT_H_
#include <iostream>
using namespace std;
class Point {
public:
void setX(int x);
int getX();
void setY(int y);
int getY();
private:
int m_X;
int m_Y;
};
#endif
注意如果头文件名是 point.h,则对应的语法就是#ifndef _POINT_H_,
似乎没有具体的写法,只要能标识是当前头文件就行,比如#ifndef __POINT__H_也行