2010-11-10 64 views
1

之前我有点问这个问题,但是我使用了我被告知的尝试让我的程序工作:多个类中使用的函数

这可能是因为我是C++的菜鸟,但由于我的问题我使用#ifndef时遇到了麻烦类包含相同的.h文件。 sh和th以及main.cpp需要在rh

中定义的结构我在我的主cpp文件

中有

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

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

并且在我的每个sh和th文件中都有一个

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

以及编译器在rh文件中给出了关于expected nested-name-specifier before "namespace"unqualified id before using namespace std;expected ';' before "namespace"的错误,即使我在rh文件中的所有内容都是:

#include <iostream> 

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

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

+1

什么是'#endlif'?你的意思是'#endif' – Chubsdad 2010-11-10 03:01:21

回答

4

#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

等。

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

+2

如果你这样做,你不需要'#include'周围的'#if'块。 – 2010-11-10 03:22:03

0

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

是否有可能您认为具有“struct r”语句的语句DEFINES r用于您的程序?

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

#ifndef R_H 
#define R_H 
#include <iostream> 

using namespace std; 

struct r{ 
//code 
}; 

#endif 

(如andand已经指出的那样)

注:我使用的定义R_H而不是R软,以避免混乱。你想在结构中使用r,在你的头文件中使用R_H作为你的定义(呃,实际上是模块的名字+“_H”)。

0

编译指令如#include#ifdef是“C预处理器”的一部分,它实际上是与C不同的编程语言。因此预处理器不会看到您的struct r。你需要像这样在你R.H:

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

这就是为什么你最好还是采用传统的包括@andand描述警卫。