一个C++问题,关于类的。能帮我解决的给加分

来源:百度知道 编辑:UC知道 时间:2024/05/10 19:08:38
我写了一个头文件Stack.h。内容是:
typedef struct IStack{
numtype date;
struct IStack *next;
}intstack;
typedef struct CStack{
char date;
struct CStack *next;
}charstack;

class IntStack{};
class CharStack{};
限于篇幅原因,类的内容没有贴出来,主要写的就是:一个成员变量,是上面定义的结构体指针,还有几个函数。
我把这个头文件写好后,然后我又写了两个头文件,都用到了这个头文件里面的类和结构体,我也包含了这个头文件,但是编译不过去,有4个错误,说我的两个结构体和类重新定义了。但是如果我把这个头文件的内容和另一个头文件合并成一个,这样再让第三个使用,却没有问题了,或者把两个头文件合并成一个,也没有问题。而只要第一个头文件被两个以上的头文件或者主程序的cpp文件包含,就马上出编译错误,内容都是重新定义了。这到底是什么意思呢?

原因是多次包含,有可能会出现重复定义.

可这样解决:
#ifndef _IStack
#define _IStack

typedef struct IStack{
numtype date;
struct IStack *next;
}intstack;

#endif

/***********************/

#ifndef _CStack
#define _CStack

typedef struct CStack{
char date;
struct CStack *next;
}charstack;

#endif

/***********************/

#ifndef _IntStack
#define _IntStack

class IntStack{};

#endif

/***********************/

#ifndef _CharStack
#define _CharStack

class CharStack{};

#endif