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

适用#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_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;
}
#endif

问题解决


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值