【问题标题】:functions used in multiple classes多个类中使用的函数
【发布时间】:2011-05-07 15:35:59
【问题描述】:

我之前问过这个问题,但我使用了我被告知的内容来尝试让我的程序运行:

这可能是因为我是 C++ 的菜鸟,但由于我的类包含相同的 .h 文件的问题,我无法使用 #ifndef。 s.h 和 t.h 和 main.cpp 都需要 r.h 中定义的结构

我有

#include "s.h"
#include "t.h"

#ifndef r
#include "r.h"
#endlif

在我的主 cpp 文件中

在我的每个 s.h 和 t.h 文件中,都有一个

#ifndef r
#include "r.h"
#endlif
// and then its class

同样,但编译器在 r.h 文件中给了我关于 expected nested-name-specifier before "namespace"、unqualified id before using namespace std;、expected ';' before "namespace" 的错误,即使我在 r.h 文件中只有:

#include <iostream>

using namespace std;
struct r{
// code
};

是主 cpp 没有导入某些库或其他东西引起的问题吗?我该如何解决?

【问题讨论】:

  • 什么是'#endlif'?你的意思是'#endif'

标签: c++ header include include-guards


【解决方案1】:

#ifndef 需要进入头文件以防止多次包含它。所以,你的 s.h 看起来像这样:

#ifndef S_H
#define S_H

// All of your s.h declarations go here

#endif

r.h 看起来像这样:

#ifndef R_H
#define R_H

// All of your r.h declarations go here

#endif

等等。

这可以防止头文件被多次包含。如果在一个编译单元中多次包含同一个头文件,编译器可能会抱怨同一个符号被多次声明。如果递归包含相同的标头集合,它还可能在编译期间引发无限循环。

【讨论】:

  • 如果你这样做,你就不需要在你的#include 周围加上#if 块。
【解决方案2】:

我希望您使用 r、s 和 t 来简化您的问题。

您是否可能认为带有“struct r”的语句为您的程序定义了 r?

这是两种不同的定义。一个是结构定义,但您想使用定义:

#ifndef R_H
#define R_H
#include <iostream>

using namespace std;

struct r{
//code
};

#endif

(正如并且已经指出的)

注意:我使用定义 R_H 而不是 r 以避免混淆。您想将 r 用于您的结构,将 R_H 用于您的标头中的定义(嗯,实际上是模块的名称 +“_H”)。

【讨论】:

    【解决方案3】:

    像#include 和#ifdef 这样的编译器指令是“C 预处理器”的一部分,它实际上是与C 不同的编程语言。所以预处理器看不到你的struct r。你的 r.h 中需要这样的东西:

    #include <iostream>
    #define r
    using namespace std;
    struct something_that_isnt_called_just_r{
    // code
    };
    

    这就是为什么你最好使用@andand 描述的传统包含守卫。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2020-07-03
      • 2023-03-25
      相关资源
      最近更新 更多