C++头文件防止重复包含

来源:互联网 发布:mac如何编辑srt文件 编辑:程序博客网 时间:2024/06/03 06:48

适用#ifndef #endif命令可以防止头文件重复包含。
在C++中,一个变量或者类只能定义一次。
假设定义了头文件testclass.h代码如下:


class testclass{private:    //成员变量int a;int b;public:testclass();testclass(int,int); //构造函数};testclass::testclass(){this->a=0;this->b=0;}testclass::testclass(int a,int b){this->a=a;this->b=b;}

又有testclassb.h代码如下:

#include"testclass.h"class testclassb{testclass c;testclass d;int x;int y;testclassb(testclass,testclass,int,int);};testclassb::testclassb(testclass c,testclass d,int x,int y){this->c=c;this->d=d;this->x=x;this->y=y;}

主函数代码如下:

#include<iostream>#include "testclass.h"#include "testclassb.h"using namespace std;int main(){cout<<"test!"<<endl;system("pause");}

这时候编译,编译器会提示testclass类重定义。因为在testclassb中包含了testclass头文件 在主函数中 既包含了testclass又包含了testclassb。而testclassb中又包含了testclass 相当于testclass被定义了两次,故会报错

解决方法:使用#ifndef指令。只要将testclass.h文件内容修改如下:

#ifndef TESTCLASS_H#define TESTCLASS_Hclass testclass{private:    //成员变量int a;int b;public:testclass();testclass(int,int); //构造函数};testclass::testclass(){this->a=0;this->b=0;}testclass::testclass(int a,int b){this->a=a;this->b=b;}#endif

问题解决


原创粉丝点击