头文件C ++的多个包含 [英] Multiple inclusion of header file c++

查看:62
本文介绍了头文件C ++的多个包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在C ++代码中多次包含头文件有疑问.

I have a problem regarding multiple inclusion of header file in C++ code.

例如,我有三个类X,Y,Z.X和Y都是从基类Z派生的.我想在Y中创建X的实例.代码将像这样.

Say for example, I have three classes X, Y, Z. X and Y are derived from base class Z. And I want to create an instance of X in Y. The code will go like this.

class Z { …some code… };

class X: public Z { …some code… };  //here #include header of class Z added

class Y: public Z  //here #include header of class Z added as well as of X class
{
private:
   X* mX;    //instance of X 

   …some code…
};

因此,在基类所有方法的多重定义中出现了.我该如何解决这个问题?

So in this multiple definition of all methods of base class arises. How can I cope with this problem?

推荐答案

使用包含卫士"( Wikipedia链接)

#ifndef MYHEADER_H
#define MYHEADER_H

// header file contents go here...

#endif // MYHEADER_H

这是惯用的代码,任何经验丰富的C和C ++程序员都可以轻松识别.将 MYHEADER_H 更改为您特定的内容,例如,如果标头定义了名为 CustomerAccount 的类,则可以调用后卫 CUSTOMERACCOUNT_H .

This is idiomatic code, easily recognizable by any seasoned C and C++ programmer. Change MYHEADER_H to something specific to you, for example if the header defines a class named CustomerAccount, you can call the guard CUSTOMERACCOUNT_H.

在您的特定情况下,每个类都有一个单独的头文件/源文件.Z类的头文件将具有包含保护:

In your specific case, have a separate header/source file for each class. The header file for the Z class will have an include guard:

#ifndef Z_H
#define Z_H

// Code of Z class

#endif Z_H

现在,X和Y的标头都可以安全地包含 zh -它只会真正包含在同时包含 xh的 .cpp 文件中一次 yh ,并且不会重复.

Now, the headers of both X and Y can include z.h safely - it will only really be included once in a .cpp file that includes both x.h and y.h and no duplication will occur.

请始终记住,在C和C ++中,真正要编译的是源文件(.c或.cpp),而不是头文件.头文件只是被预处理器复制粘贴"到包含头文件的源文件中.

Always keep in mind that in C and C++ what's really gets compiled are the source (.c or .cpp) files, not the header files. The header files are just "copy-pasted" by the preprocessor into the sources files that include them.

这篇关于头文件C ++的多个包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆