C++类,对 #ifdef,#define 和 #endif 的守卫混乱

C++ classes, confusion in reguards to #ifdef, #define and #endif

本文关键字:#endif 守卫 混乱 #define #ifdef C++      更新时间:2023-10-16

好的,所以我们在我的C++课上讲课,在上一堂课中我们了解到,如果你多次 #include 同一个文件中的同一个类,可能会发生不好的事情,防止这种情况的方法是在头文件中使用 #ifdef、#define 和 #endif。 所以这只是我正在尝试编写的一个简单的程序, 由于这个家伙#,它失败了。似乎 #ifdef 之后的代码被编译器忽略了。这里的问题出在哪里?

这是程序,它由 3 个文件组成,另请注意,我知道如果没有 .h 文件中的 # 东西,程序可以正常工作,并且在这个特定的程序中,我什至不需要它们。我正在做一个大项目,我需要使用它们,但它们只是不起作用。

谢谢。

==========主

文件===

========
#include "Circle.h"
int main()
{
    Circle C(5);
    C.output();
    return 0;
}
=======

==Circle.h 文件=

==========
#ifdef CIRCLE_H
#define CIRCLE_H

#include <iostream>
using namespace std;
class Circle
{
public:
    Circle(int);
    void output();
private:
    int n;

};

#endif
======

==圆圈.cpp文件========

#include "Circle.h"

Circle::Circle(int numb)
{
    n=numb;
}

void Circle::output()
{
    cout<<"The number is "<<n<<endl;
}

你应该使用#ifndef CIRCLE_H而不是#ifdef CIRCLE_H。它的意思是"如果未定义"。

问题是,你使用了错误的预处理器结构:

#ifdef CIRCLE_H //#ifdef is not the right one!
#define CIRCLE_H
//...
#endif

您应该改用 #ifndef。为什么?

#ifdef意味着if token with name, placed after this instruction is already defined, then....你认为这会奏效吗?包含此文件时,CIRCLE_H不会在任何地方定义,因此#ifdef CIRCLE_H将始终计算为 false,并且 #ifdef#endif 之间的内容将始终被丢弃。

但是当你写这个时:

#ifndef CIRCLE_H
#define CIRCLE_H
//...
#endif

你说:if CIRCLE_H has not yet been defined(这是真的,当第一次包含文件时(,then define CIRCLE_H and proceed. 然后定义CIRCLE_H,每个下一个包含都不会通过此#ifndef,因为CIRCLE_H已经存在。