C++中的#define里面的结构

Ada*_*ith 2 c++ precompiled-headers c-preprocessor

作为C++的新手,我不太了解我遇到的一些指令,例如:

#ifndef BOT_H_
#define BOT_H_

#include "State.h"

/*
    This struct represents your bot in the game of Ants
*/
struct Bot
{
    State state;

    Bot();

    void playGame();    //plays a single game of Ants

    void makeMoves();   //makes moves for a single turn
    void endTurn();     //indicates to the engine that it has made its moves
};

#endif //BOT_H_
Run Code Online (Sandbox Code Playgroud)

我不明白的是"#ifndef BOT_H_"和"#define - #endif"

从我收集的内容中,它定义了一个常量BOT_H_,如果在预编译器查看它时尚未定义它.我实际上并没有得到它内部的结构是一个常量,以及如何让我访问其中的函数.

我也不明白为什么我们这样做呢?我曾经使用过C++而我没有使用.h文件,所以它可能很容易让我失踪.

Abd*_*ahC 10

这被称为包含保护,以防止头文件的内容被多次#included.

也就是说,它防止头文件的内容被复制到#include它的文件中,当它之前已经#included它时.

#define不定义为一个常数struct,但它只是定义没有值的常量.如果先前已定义该常量,则不会重新声明该结构.


Cat*_*lus 5

它被称为"包括守卫".当多次包含标头时,它可以保护您免受重新定义的影响.也有非标准#pragma once做同样的事情,但可能无处不在.