C++类,对 #ifdef,#define 和 #endif 的守卫混乱
C++ classes, confusion in reguards to #ifdef, #define and #endif
好的,所以我们在我的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
已经存在。
- #if 如何工作?我误解了 #if~#endif 的形式吗?
- 已经在 .obj 中定义,即使有 #ifndef #define #endif
- 如何在 c++ 中正确命名包含守卫
- 为什么我们保留互斥锁而不是每次都守卫前声明它
- 如何编写函数来替换 #ifdef 和 #endif 对
- #include inside #if - #endif
- C++类,对 #ifdef,#define 和 #endif 的守卫混乱
- #if-#endif中的C++行数限制
- #include 守卫不起作用 - 或者我不明白
- #if /#endif 预处理指令
- C++ #if #elif #endif似乎不起作用
- 为什么在 c++ 中包含守卫不是默认设置
- 如何将C预处理器仅应用于某些(#if/#endif)指令
- 如何让 emacs 像'{'和 '}' 一样对待 #ifdef 和 #endif?
- 米斯拉警告包括守卫
- C包括守卫
- 哪个更重要?头守卫、命名空间和include
- 放置 #ifdef __cplusplus 外置"C"的最佳位置在哪里{#endif
- 警告:#endif指令末尾有多余的标记
- 是否可以模拟将#ifdef放置在另一个#ifdef #endif中的效果?